// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
using InterpriseSuiteEcommerceCommon.DTO;
using InterpriseSuiteEcommerceCommon.Extensions;
using InterpriseSuiteEcommerceCommon.InterpriseIntegration;
using InterpriseSuiteEcommerceCommon.Tool;

namespace InterpriseSuiteEcommerceCommon
{
    /// <summary>
    /// Summary description for AppLogic.
    /// </summary>

    public delegate void ApplicationStartRoutine();
    public delegate string GetLicenseProductLevel();
    public delegate bool GetIsMLLevel();

    public class AppLogic
    {

        public static int NumProductsInDB = 0; // set to # of products in the db on Application_Start. Not updated thereafter
        public static bool CachingOn = false;  // set to true in Application_Start if AppConfig:CacheMenus=true

        public static AppConfigs AppConfigTable; // LOADED in application_start of the respective web project
        public static StringResources StringResourceTable; // LOADED in application_start of the respective web project

        public static Hashtable ImageFilenameCache = new Hashtable(); // Caching is ALWAYS on for images, cache of category/section/product/etc image filenames from LookupImage. Added on first need
        static private EntityHelper m_CategoryEntityHelper = null;
        static private EntityHelper m_SectionEntityHelper = null;
        static private EntityHelper m_ManufacturerEntityHelper = null;
        static private EntityHelper m_AttributeEntityHelper = null;

        public static ApplicationStartRoutine m_RestartApp;
        public static GetLicenseProductLevel m_ProductLevel;
        public static GetIsMLLevel m_ProductIsML;

        public static readonly string[] ro_SupportedEntities = { "Category", "Department", "Manufacturer", "Attribute" };

        public static AspNetHostingPermissionLevel TrustLevel;

        public static bool ReplaceImageURLFromAssetMgr = false;

        public static string MicropayProductID = string.Empty;
        public static string MicropayVariantID = string.Empty;
        public static string AdHocProductID = string.Empty;
        public static string AdHocVariantID = string.Empty;

        public static readonly string ro_DefaultProductXmlPackage = "product.variantsinrightbar.xml.config";
        public static readonly string ro_DefaultProductPackXmlPackage = "product.packproduct.xml.config";
        public static readonly string ro_DefaultProductKitXmlPackage = "product.kitproduct.xml.config";
        public static readonly string ro_DefaultEntityXmlPackage = "entity.grid.xml.config";
        public static readonly string ro_DefaultCelebrityXmlPackage = "entity.grid.xml.config";

        public static readonly string MobileDefaultProductXmlPackage = "product.SimpleProduct.xml.config";
        public static readonly string MobileDefaultProductKitXmlPackage = "product.kitproduct.xml.config";
        public static readonly string MobileDefaultProductMatrixXmlPackage = "product.matrixproduct.xml.config";

        public static readonly string ro_NotApplicable = "N/A";

        public static readonly string ro_CCNotStoredString = "Not Stored";
        public static readonly string ro_TXModeAuthCapture = "AUTH CAPTURE";
        public static readonly string ro_TXModeAuthOnly = "AUTH";
        public static readonly string ro_TXStateAuthorized = "AUTHORIZED";
        public static readonly string ro_TXStateCaptured = "CAPTURED";
        public static readonly string ro_TXStateVoided = "VOIDED";
        public static readonly string ro_TXStateRefunded = "REFUNDED";
        public static readonly string ro_TXStateFraud = "FRAUD";
        public static readonly string ro_TXStateUnknown = "UNKNOWN"; // possible, but not used
        public static readonly string ro_TXStatePending = "PENDING";

        public static readonly int ro_GenericTaxClassID = 1;

        public static readonly string ro_OK = "OK";
        public static readonly string ro_TBD = "TBD";
        public static readonly string ro_3DSecure = "3Denrollee";
        public static readonly string ro_PROTX = "Interprise.Presentation.Customer.PaymentGateway.Protx.ProtxGatewayControl";
        public static readonly string ro_INTERPRISE_GATEWAY_AUTHORIZATION_FAILED = "GatewayAuthorizationFailed";
        public static readonly string ro_INTERPRISE_GATEWAY_V2 = "Interprise.Presentation.Customer.PaymentGateway.ITGPIv2.InterpriseGatewayControl";
        public static readonly string ro_CBN_MODE = "CBMode";

        public static readonly string ro_SKUMicropay = "MICROPAY";

        public static readonly string ro_PMMicropay = "MICROPAY";
        public static readonly string ro_PMCreditCard = "CREDITCARD";
        public static readonly string ro_PMECheck = "ECHECK";
        public static readonly string ro_PMRequestQuote = "QUOTE";
        public static readonly string ro_PMCOD = "COD";
        public static readonly string ro_PMCODMoneyOrder = "CODMONEYORDER";
        public static readonly string ro_PMCODCompanyCheck = "CODCOMPANYCHECK";
        public static readonly string ro_PMCODNet30 = "CODNET30";
        public static readonly string ro_PMPurchaseOrder = "PURCHASEORDER";
        public static readonly string ro_PMPayPal = "PAYPAL";
        public static readonly string ro_PMPayPalExpress = "PAYPALEXPRESS";
        public static readonly string ro_PMPayPalExpressMark = "PAYPALEXPRESSMARK"; // used for checkout flow only, order is stored as ro_PMPayPalExpress
        public static readonly string ro_PMCheckByMail = "CHECKBYMAIL";
        public static readonly string ro_PMBypassGateway = "BYPASSGATEWAY";

        // these are pulled from string resources:
        public static readonly string ro_PMMicropayForDisplay = "(!pm.micropay.display!)";
        public static readonly string ro_PMCreditCardForDisplay = "(!pm.creditcard.display!)";
        public static readonly string ro_PMECheckForDisplay = "(!pm.echeck.display!)";
        public static readonly string ro_PMRequestQuoteForDisplay = "(!pm.requestquote.display!)";
        public static readonly string ro_PMCODForDisplay = "(!pm.cod.display!)";
        public static readonly string ro_PMCODMoneyOrderForDisplay = "(!pm.codmoneyorder.display!)";
        public static readonly string ro_PMCODCompanyCheckForDisplay = "(!pm.codcompanycheck.display!)";
        public static readonly string ro_PMCODNet30ForDisplay = "(!pm.codnet30.display!)";
        public static readonly string ro_PMPurchaseOrderForDisplay = "(!pm.purchaseorder.display!)";
        public static readonly string ro_PMPayPalForDisplay = "(!pm.paypal.display!)";
        public static readonly string ro_PMPayPalExpressForDisplay = "(!pm.paypalexpress.display!)";
        public static readonly string ro_PMCheckByMailForDisplay = "(!pm.checkbymail.display!)";
        public static readonly string ro_PMBypassGatewayForDisplay = "(!pm.bypassgateway.display!)";

        public static readonly string PasswordValuePlaceHolder = "********";
        public static string ro_SkinCookieName = string.Concat("SkinID_", InterpriseHelper.ConfigInstance.WebSiteCode);
        public static bool AppIsStarted = false;


        public static bool IsAllowFractional = false;
        public static int InventoryDecimalPlacesPreference = 2;

        public const string MAX_QUANTITY_INPUT_Dec = "9999999.999999";
        public const string MAX_QUANTITY_INPUT_NoDec = "9999999";

        public const string VALIDATECAPTCHA = "validate-captcha";
        public const string VALIDATE_RECAPTCHA = "validate-recaptcha";
        public const string SAVE_LEAD = "save-lead";
        public const string RENDER_STATES = "render-states";

        public const string EMAIL_HAS_DUPLICATES = "EmailHasDuplicates";
        public const string LEAD_NAME_HAS_DUPLICATES = "LeadHasDuplicates";
        public const string CAPTCHA_MISMATCH = "mismatch";
        public const string CAPTCHA_MATCH = "match";
        public const string UNDEFINED_TASK = "task is undefined";
        public const string UNDEFINED_RESULT = "Undefined Result";
        
        public const string SUBJECT = "leadform.aspx.21";
        public const string FROM_ADDRESS = "MailMe_FromAddress";
        public const string FROM_NAME = "MailMe_FromName";
        public const string TO_ADDRESS = "MailMe_ToAddress";
        public const string TO_NAME = "MailMe_ToName";

        public const string SOURCE_CODE = "Internet";
        public const string SEND_LF_NOTIFICATION = "SendLeadFormNotification";
        public const string XML_LF_NOTIFICATION = "XmlPackage.LeadFormNotification";
        public const string MAIL_SERVER = "MailMe_Server";

        public struct CurrentEntity
        {
            public CurrentEntity(bool isNull)
            {
                IsNull = isNull;
                EntityType = string.Empty;
                EntityID = string.Empty;
            }

            public string EntityType;
            public string EntityID;
            public bool IsNull;
        }

        public AppLogic()
        {
            Interprise.Connectivity.Database.Configuration.Design.AppConfig.InterpriseConfiguration a = InterpriseHelper.ConfigInstance;
            ro_SkinCookieName = string.Concat("SkinID_", a.WebSiteCode);
        }

        public static int DefaultSkinID()
        {
            return AppLogic.AppConfigUSInt("DefaultSkinID");
        }

        public static string LiveServer()
        {
            return AppLogic.AppConfig("LiveServer");
        }

        public static bool VATIsEnabled()
        {
            return AppLogic.AppConfigBool("VAT.Enabled");
        }

        public static string MailServer()
        {
            return AppLogic.AppConfig("MailMe_Server");
        }

        public static string AdminDir()
        {
            return AppLogic.AppConfig("AdminDir");
        }

        public static string HomeTemplate()
        {
            return AppLogic.AppConfig("HomeTemplate");
        }

        public static bool RedirectLiveToWWW()
        {
            return AppLogic.AppConfigBool("RedirectLiveToWWW");
        }

        public static bool EventLoggingEnabled()
        {
            return AppLogic.AppConfigBool("EventLoggingEnabled");
        }

        public static bool HomeTemplateAsIs()
        {
            return AppLogic.AppConfigBool("HomeTemplateAsIs");
        }

        public static bool UseSSL()
        {
            return AppLogic.AppConfigBool("UseSSL");
        }

        private static int _numberOfTries = -1;

        public static int InterpriseExceptionFacadeNumberOfTries
        {
            get
            {
                if (_numberOfTries <= 0)
                {
                    try
                    {
                        _numberOfTries = Interprise.Facade.Base.BaseFacade.ConfigurationManager.ExceptionManager.ConfigurationUtility.NumberOfTries;//Interprise.Facade.Base.ExceptionManagerFacade.NumberOfTries;
                    }
                    catch { }
                }

                if (_numberOfTries <= 0)
                {
                    _numberOfTries = 3;
                }

                return _numberOfTries;
            }
        }

        public static bool IsSupportedAlternateCheckout
        {
            get
            {
                if (InterpriseHelper.ConfigInstance.LicenseInfo.ProductEdition.ToUpper() != Interprise.Licensing.Base.Shared.Enum.ProductEdition.ISB.ToString())
                    return true;
                else
                    return false;
            }
        }

        public static void CheckForScriptTag(string s)
        {
            if (s.Replace(" ", "").IndexOf("<script", StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                throw new ArgumentException("SECURITY EXCEPTION");
            }
        }

        public static string GetCurrentEntityTemplateName(string EntityName)
        {
            return GetCurrentEntityTemplateName(EntityName, string.Empty);
        }

        public static string GetCurrentEntityTemplateName(string EntityName, string UseThisEntityID)
        {
            EntityHelper helper = AppLogic.LookupHelper(EntityName);
            string eID = CommonLogic.QueryStringCanBeDangerousContent(helper.GetEntitySpecs.m_EntityName + "ID");
            if (UseThisEntityID.Length != 0)
            {
                eID = UseThisEntityID;
            }
            XmlNode n = helper.m_TblMgr.SetContext(eID);
            string HT = XmlCommon.XmlField(n, "TemplateName").ToLowerInvariant();
            while (HT.Length == 0 && (n = helper.m_TblMgr.MoveParent(n)) != null)
            {
                HT = XmlCommon.XmlField(n, "TemplateName").ToLowerInvariant();
            }
            if (HT.Length != 0)
            {
                if (!HT.EndsWith(".ascx", StringComparison.InvariantCultureIgnoreCase))
                {
                    HT = HT + ".ascx";
                }
            }
            return HT;
        }

        private static string ENTITY_CACHE_KEY = "EntityHelpers_Cache_Key";

        public static void InvalidEntityHelperXmlCache()
        {
            HttpRuntime.Cache.Remove(ENTITY_CACHE_KEY);
        }

        public static void ReloadAppConfigs()
        {
            AppConfigTable = AppConfigs.GetAll();
        }

        public static void ReloadStringResources()
        {
            LoadStringResourcesFromDB(true);
        }

        public static void ReloadImageFileNameCache()
        {
            ImageFilenameCache.Clear();
        }

        public static EntityHelper CategoryEntityHelper
        {
            get
            {
                if (m_CategoryEntityHelper == null)
                {
                    m_CategoryEntityHelper = new EntityHelper(0, EntityDefinitions.LookupSpecs("Category"), true);
                }
                return m_CategoryEntityHelper;
            }
        }

        public static EntityHelper SectionEntityHelper
        {
            get
            {
                if (m_SectionEntityHelper == null)
                {
                    m_SectionEntityHelper = new EntityHelper(0, EntityDefinitions.LookupSpecs("Department"), true);
                }
                return m_SectionEntityHelper;
            }
        }

        public static EntityHelper ManufacturerEntityHelper
        {
            get
            {
                if (m_ManufacturerEntityHelper == null)
                {
                    m_ManufacturerEntityHelper = new EntityHelper(0, EntityDefinitions.LookupSpecs("Manufacturer"), true);
                }
                return m_ManufacturerEntityHelper;
            }
        }

        public static EntityHelper AttributeEntityHelper
        {
            get
            {
                if (m_AttributeEntityHelper == null)
                {
                    m_AttributeEntityHelper = new EntityHelper(0, EntityDefinitions.LookupSpecs("Attribute"), true);
                }
                return m_AttributeEntityHelper;
            }
        }

        public static void ReloadEntityHelper(string entity)
        {
            switch (entity.ToUpperInvariant())
            {
                case "CATEGORY":
                    m_CategoryEntityHelper = new EntityHelper(0, EntityDefinitions.LookupSpecs("Category"), true);
                    break;

                case "SECTION":
                case "DEPARTMENT":
                    m_SectionEntityHelper = new EntityHelper(0, EntityDefinitions.LookupSpecs("Department"), true);
                    break;

                case "MANUFACTURER":
                    m_ManufacturerEntityHelper = new EntityHelper(0, EntityDefinitions.LookupSpecs("Manufacturer"), true);
                    break;
                case "ATTRIBUTE":
                    m_AttributeEntityHelper = new EntityHelper(0, EntityDefinitions.LookupSpecs("Attribute"), true);
                    break;
            }

            InvalidEntityHelperXmlCache();
        }

        public static void RequireSecurePage()
        {
            if (!AppLogic.UseSSL()) return;
            
            if (AppLogic.OnLiveServer() && CommonLogic.ServerVariables("SERVER_PORT_SECURE") != "1")
            {
                string query = CommonLogic.ServerVariables("QUERY_STRING");
                if (!query.IsNullOrEmptyTrimmed()) query = "?" + query;

                HttpContext.Current.Response.Redirect(AppLogic.GetStoreHTTPLocation(true) + CommonLogic.GetThisPageName(false) + query);
            }
        }

        // This is expensive to call, do not call it unless you absolutely have to:
        public static AspNetHostingPermissionLevel DetermineTrustLevel()
        {
            foreach (AspNetHostingPermissionLevel trustLevel in
                    new AspNetHostingPermissionLevel[] {
                AspNetHostingPermissionLevel.Unrestricted,
                AspNetHostingPermissionLevel.High,
                AspNetHostingPermissionLevel.Medium,
                AspNetHostingPermissionLevel.Low,
                AspNetHostingPermissionLevel.Minimal 
            })
            {
                try
                {
                    new AspNetHostingPermission(trustLevel).Demand();
                }
                catch (System.Security.SecurityException)
                {
                    continue;
                }

                return trustLevel;
            }

            return AspNetHostingPermissionLevel.None;
        }

        public static System.Collections.Generic.Dictionary<string, EntityHelper> MakeEntityHelpers()
        {
            System.Collections.Generic.Dictionary<string, EntityHelper> m_EntityHelpers = new System.Collections.Generic.Dictionary<string, EntityHelper>();
            m_EntityHelpers.Add("Category", new EntityHelper(EntityDefinitions.LookupSpecs("Category")));
            m_EntityHelpers.Add("Department", new EntityHelper(EntityDefinitions.LookupSpecs("Department")));
            m_EntityHelpers.Add("Manufacturer", new EntityHelper(EntityDefinitions.LookupSpecs("Manufacturer")));
            m_EntityHelpers.Add("Attribute", new EntityHelper(EntityDefinitions.LookupSpecs("Attribute")));
            return m_EntityHelpers;
        }

        public static string GetLanguageCode(string sLocaleSetting)
        {
            string tmp = string.Empty;
            using (DataSet ds = DB.GetDS("SELECT * FROM eCommerceWebLocaleView with (NOLOCK)", true, DateTime.Now.AddHours(1)))
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (sLocaleSetting == Localization.CheckLocaleSettingForProperCase(DB.RowField(row, "ShortString")))
                    {
                        tmp = DB.RowField(row, "LanguageDescription");
                    }
                }
            }
            return tmp;
        }

        public static string GetLocaleDefaultCurrency(string LocaleSetting)
        {
            string tmp = string.Empty;


            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, "select DefaultCurrencyID from EcommerceLocaleSetting with (NOLOCK) where Name=" + DB.SQuote(LocaleSetting)))
                {
                    if (rs.Read())
                    {
                        tmp = DB.RSField(rs, "DefaultCurrencyID");
                    }
                }
            }

            if (tmp.Length == 0)
            {
                return Localization.GetPrimaryCurrency();
            }
            else
            {
                return Currency.GetCurrencyCode(tmp);
            }
        }

        // just removes all <....> markup from the text string. this is brute force, and may or may not give
        // the right aesthetic result to the text. it just brute force removes the markup tags
        public static string StripHtml(string s)
        {
            return Regex.Replace(s, @"<(.|\n)*?>", string.Empty, RegexOptions.Compiled);
        }
        // input CardNumber can be in plain text or encrypted, doesn't matter:
        public static string SafeDisplayCardNumber(string CardNumber, string Table, int TableID)
        {
            if (CardNumber == null || CardNumber.Length == 0)
            {
                return string.Empty;
            }
            string SaltKey = string.Empty;
            string CardNumberDecrypt = Security.UnmungeString(CardNumber, SaltKey);
            if (CardNumberDecrypt.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                CardNumberDecrypt = CardNumber;
            }
            if (CardNumberDecrypt == AppLogic.ro_CCNotStoredString)
            {
                return string.Empty;
            }
            if (CardNumberDecrypt.Length > 4)
            {
                return "****" + CardNumberDecrypt.Substring(CardNumberDecrypt.Length - 4, 4);
            }
            else
            {
                return string.Empty;
            }
        }

        // input CardExtraCode can be in plain text or encrypted, doesn't matter:
        public static string SafeDisplayCardExtraCode(string CardExtraCode)
        {
            if (CardExtraCode == null || CardExtraCode.Length == 0)
            {
                return string.Empty;
            }
            string CardExtraCodeDecrypt = Security.UnmungeString(CardExtraCode);
            if (CardExtraCodeDecrypt.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                CardExtraCodeDecrypt = CardExtraCode;
            }
            return "*".PadLeft(CardExtraCodeDecrypt.Length, '*');
        }

        // returns empty string, or decrypted card extra code from appropriate session state location
        public static string GetCardExtraCodeFromSession(Customer ThisCustomer)
        {
            string CardExtraCode = Security.UnmungeString(ThisCustomer.ThisCustomerSession["CardExtraCode"]);
            return CardExtraCode;
        }

        public static int NumLocaleSettingsInstalled()
        {
            int N = 0;
            string CacheName = "NumLocaleSettingsInstalled";
            if (AppLogic.CachingOn)
            {
                string s = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
                if (s != null)
                {
                    N = Localization.ParseUSInt(s);
                }
            }
            if (N == 0)
            {
                N = DB.GetSqlN("SELECT COUNT(*) AS N FROM SystemSellingLanguage with (NOLOCK) WHERE IsIncluded = 1 ");
            }
            if (N == 0)
            {
                N = 1;
            }
            if (CachingOn)
            {
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, N, AppLogic.CacheDurationMinutes());
            }
            return N;
        }
        // stores cardextracode in appropriate session, encrypted
        public static void StoreCardExtraCodeInSession(Customer ThisCustomer, string CardExtraCode)
        {
            ThisCustomer.ThisCustomerSession["CardExtraCode"] = Security.MungeString(CardExtraCode);
        }

        public static void ClearCardExtraCodeInSession(Customer ThisCustomer)
        {
            // wipe from both sessions, it was only in one of them anyway, but wipe both for safety:
            ThisCustomer.ThisCustomerSession["CardExtraCode"] = "111111111";
            ThisCustomer.ThisCustomerSession["CardExtraCode"] = string.Empty;
        }

        public static void StoreCardNumberInSession(Customer ThisCustomer, string CardNumber, string CardNumberSalt, string CardNumberIV)
        {
            ThisCustomer.ThisCustomerSession["CardNumber"] = Security.MungeString(CardNumber);
            ThisCustomer.ThisCustomerSession["CardNumberSalt"] = Security.MungeString(CardNumberSalt);
            ThisCustomer.ThisCustomerSession["CardNumberIV"] = Security.MungeString(CardNumberIV);
        }

        public static void ClearCardNumberInSession(Customer ThisCustomer)
        {
            // wipe from both sessions, it was only in one of them anyway, but wipe both for safety:
            ThisCustomer.ThisCustomerSession["CardNumber"] = "111111111";
            ThisCustomer.ThisCustomerSession["CardNumber"] = string.Empty;
            ThisCustomer.ThisCustomerSession["CardNumberSalt"] = "111111111";
            ThisCustomer.ThisCustomerSession["CardNumberSalt"] = string.Empty;
            ThisCustomer.ThisCustomerSession["CardNumberIV"] = "111111111";
            ThisCustomer.ThisCustomerSession["CardNumberIV"] = string.Empty;
        }

        public static void StoreCardIssueNumberInSession(Customer ThisCustomer, string CardIssueNumber, string CardIssueNumberSalt, string CardIssueNumberIV)
        {
            ThisCustomer.ThisCustomerSession["CardIssueNumber"] = Security.MungeString(CardIssueNumber);
            ThisCustomer.ThisCustomerSession["CardIssueNumberSalt"] = Security.MungeString(CardIssueNumberSalt);
            ThisCustomer.ThisCustomerSession["CardIssueNumberIV"] = Security.MungeString(CardIssueNumberIV);
        }

        public static void ClearCardIssueNumberInSession(Customer ThisCustomer)
        {
            ThisCustomer.ThisCustomerSession["CardIssueNumber"] = "111111111";
            ThisCustomer.ThisCustomerSession["CardIssueNumber"] = string.Empty;
            ThisCustomer.ThisCustomerSession["CardIssueNumberSalt"] = "111111111";
            ThisCustomer.ThisCustomerSession["CardIssueNumberSalt"] = string.Empty;
            ThisCustomer.ThisCustomerSession["CardIssueNumberIV"] = "111111111";
            ThisCustomer.ThisCustomerSession["CardIssueNumberIV"] = string.Empty;
        }

        public static void GenerateCreditCardCodeSaltIV(Customer ThisCustomer)
        {
            string salt = Convert.ToBase64String(InterpriseHelper.GenerateSalt());
            string vector = Convert.ToBase64String(InterpriseHelper.GenerateVector());
            ThisCustomer.ThisCustomerSession["CreditCardCodeSalt"] = salt;
            ThisCustomer.ThisCustomerSession["CreditCardCodeVector"] = vector;
        }
        public static string EncryptCreditCardCode(Customer ThisCustomer, string cardCode)
        {
            string cardCodeEnc = string.Empty;
            string salt = ThisCustomer.ThisCustomerSession["CreditCardCodeSalt"].ToString();
            string vector = ThisCustomer.ThisCustomerSession["CreditCardCodeVector"].ToString();

            if (!salt.IsNullOrEmptyTrimmed() && vector.IsNullOrEmptyTrimmed()) return cardCodeEnc;

            var cryptoService = new Interprise.Licensing.Base.Services.CryptoServiceProvider();
            cardCodeEnc = cryptoService.Encrypt(cardCode, Convert.FromBase64String(salt), Convert.FromBase64String(vector));

            return cardCodeEnc;
        }

        public static string DecryptCreditCardCode(Customer ThisCustomer, string cardCode)
        {
            string salt = ThisCustomer.ThisCustomerSession["CreditCardCodeSalt"].ToString();
            string vector = ThisCustomer.ThisCustomerSession["CreditCardCodeVector"].ToString();
            Interprise.Licensing.Base.Services.CryptoServiceProvider cryptoService = new Interprise.Licensing.Base.Services.CryptoServiceProvider();
            string cardCodeDec = cryptoService.Decrypt(Convert.FromBase64String(cardCode), Convert.FromBase64String(salt), Convert.FromBase64String(vector));
            return cardCodeDec;
        }

        public static void ClearCreditCardCodeInSession(Customer ThisCustomer)
        {
            ThisCustomer.ThisCustomerSession["CreditCardCodeSalt"] = string.Empty;
            ThisCustomer.ThisCustomerSession["CreditCardCodeVector"] = string.Empty;
        }

        public static string EncryptCardNumber(string cardNumber, ref string salt, ref string iv)
        {
            Interprise.Licensing.Base.Services.CryptoServiceProvider cryptoService = new Interprise.Licensing.Base.Services.CryptoServiceProvider();
            string cardNumberEnc = cryptoService.Encrypt(cardNumber, ref salt, ref iv);
            return cardNumberEnc;
        }

        public static bool IsSaveCardInfoChecked(Customer ThisCustomer)
        {
            bool saveCard = false;
            bool.TryParse(ThisCustomer.ThisCustomerSession["SaveCreditCardChecked"], out saveCard);
            return saveCard;
        }

        // input CardNumber can be in plain text or encrypted, doesn't matter:
        public static string AdminViewCardNumber(string CardNumber, string Table, int TableID)
        {
            if (CardNumber.Length == 0 || CardNumber == AppLogic.ro_CCNotStoredString)
            {
                return CardNumber;
            }
            string SaltKey = string.Empty;

            string CardNumberDecrypt = Security.UnmungeString(CardNumber, SaltKey);
            if (CardNumberDecrypt.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                CardNumberDecrypt = CardNumber;
            }
            return SafeDisplayCardNumber(CardNumber, Table, TableID);
        }

        // input CardNumber can be in plain text or encrypted, doesn't matter:
        public static string SafeDisplayCardNumberLast4(string CardNumber, string Table, int TableID)
        {
            string SaltKey = string.Empty;
            string CardNumberDecrypt = Security.UnmungeString(CardNumber, SaltKey);
            if (CardNumberDecrypt.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                CardNumberDecrypt = CardNumber;
            }
            if (CardNumberDecrypt == AppLogic.ro_CCNotStoredString)
            {
                return string.Empty;
            }
            if (CardNumberDecrypt.Length >= 4)
            {
                return CardNumberDecrypt.Substring(CardNumberDecrypt.Length - 4, 4);
            }
            else
            {
                return string.Empty;
            }
        }

        public static bool ItemHasVisibleBuyButton(string itemCode)
        {
            bool buyButtonVisible = false;
            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader reader = DB.GetRSFormat(con, string.Format("SELECT iwo.ShowBuyButton, iwo.IsCallToOrder FROM InventoryItem i with (NOLOCK) INNER JOIN InventoryItemWebOption iwo with (NOLOCK) ON i.ItemCode = iwo.ItemCode WHERE i.ItemCode = {0} AND iwo.WebsiteCode = {1}", DB.SQuote(itemCode), DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode))))
                {
                    buyButtonVisible = reader.Read() &&
                                        DB.RSFieldBool(reader, "ShowBuyButton") &&
                                        !DB.RSFieldBool(reader, "IsCallToOrder");
                }
            }

            return buyButtonVisible;
        }

        public static int MaxMenuSize()
        {
            int tmp = AppLogic.AppConfigUSInt("MaxMenuSize");
            if (tmp == 0)
            {
                tmp = 25;
            }
            return tmp;
        }

        // returns PM in all uppercase with only primary chars included
        public static string CleanPaymentMethod(string PM)
        {
            return PM.Replace(" ", string.Empty).Replace(".", string.Empty).Replace("(", string.Empty).Replace(")", string.Empty).Trim().ToUpperInvariant();
        }

        // returns PM in all uppercase with only primary chars included
        public static string CleanPaymentGateway(string GW)
        {
            return GW.Replace(" ", string.Empty).Replace(".", string.Empty).Replace("(", string.Empty).Replace(")", string.Empty).Trim().ToUpperInvariant();
        }

        // returns comma separate list of skin id's found on the web site, e.g. 1,2,3,4
        public static string FindAllSkins()
        {
            string CacheName = "FindAllSkins";
            if (AppLogic.CachingOn)
            {
                string s = (string)HttpContext.Current.Cache.Get(CacheName);
                if (s != null)
                {
                    return s;
                }
            }
            StringBuilder tmpS = new StringBuilder(1024);
            int MaxNumberSkins = AppLogic.AppConfigUSInt("MaxNumberSkins");
            if (MaxNumberSkins == 0)
            {
                MaxNumberSkins = 10;
            }
            for (int i = 0; i <= 100; i++)
            {
                string FN = CommonLogic.SafeMapPath("skins/skin_" + i.ToString() + "/template.ascx");
                if (CommonLogic.FileExists(FN))
                {
                    if (tmpS.Length != 0)
                    {
                        tmpS.Append(",");
                    }
                    tmpS.Append(i.ToString());
                }
            }

            if (CachingOn)
            {
                HttpContext.Current.Cache.Insert(CacheName, tmpS.ToString(), null, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()), TimeSpan.Zero);
            }
            return tmpS.ToString();
        }

        public static EntityHelper LookupHelper(System.Collections.Generic.Dictionary<string, EntityHelper> EntityHelpers, string EntityName)
        {
            string en = EntityName.Substring(0, 1).ToUpperInvariant() + EntityName.Substring(1, EntityName.Length - 1).ToLowerInvariant();
            EntityHelper h = null;
            if (EntityHelpers == null)
            {
                h = new EntityHelper(EntityDefinitions.LookupSpecs(en));
            }
            else
            {
                if (!EntityHelpers.ContainsKey(en))
                {
                    h = new EntityHelper(EntityDefinitions.LookupSpecs(en));
                }
                else
                {
                    h = (EntityHelper)EntityHelpers[en];
                }
            }
            return h;
        }

        public static EntityHelper LookupHelper(string EntityName)
        {
            EntityHelper h = null;

            switch (EntityName.ToUpperInvariant())
            {
                case "CATEGORY":
                    h = CategoryEntityHelper;
                    break;
                case "SECTION":
                case "DEPARTMENT":
                    h = SectionEntityHelper;
                    break;
                case "MANUFACTURER":
                    h = ManufacturerEntityHelper;
                    break;
                case "ATTRIBUTE":
                    h = AttributeEntityHelper;
                    break;
                default:
                    h = new EntityHelper(EntityDefinitions.LookupSpecs(EntityName));
                    break;
            }
            return h;

        }

        public static string GetCheckoutTermsAndConditions(int SkinID, string LocaleSetting, Parser UseParser, bool InitialStateIsChecked)
        {
            string CacheName = string.Format("GetCheckoutTermsAndConditions_{0}_{1}", SkinID.ToString(), LocaleSetting);
            if (AppLogic.CachingOn)
            {
                string htmlTest = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
                if (!htmlTest.IsNullOrEmptyTrimmed()) return htmlTest;
            }

            StringBuilder tmpS = new StringBuilder(4096);
            tmpS.Append("<br/><table align=\"center\" width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" style=\"border-style: dashed; border-width: 1px; border-color: #000000; \"><tr><td class=\"LightCell\">");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">");
            tmpS.Append("<input type=\"checkbox\" value=\"true\" id=\"TermsAndConditionsRead\" name=\"TermsAndConditionsRead\" " + CommonLogic.IIF(InitialStateIsChecked, " checked ", string.Empty) + ">&nbsp;");
            tmpS.Append(AppLogic.GetString("checkoutcard.aspx.3", SkinID, LocaleSetting));
            tmpS.Append("<div align=\"left\">");
            Topic t = new Topic("checkouttermsandconditions", LocaleSetting, SkinID, UseParser);
            tmpS.Append(t.Contents);
            tmpS.Append("</div>");
            tmpS.Append("</td></tr>");
            tmpS.Append("<tr><td colspan=\"2\" height=\"25\"></td></tr>");
            tmpS.Append("</table>\n");

            if (CachingOn)
            {
                HttpContext.Current.Cache.Insert(CacheName, tmpS.ToString(), null, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()), TimeSpan.Zero);
            }
            return tmpS.ToString();
        }

        public static List<XmlPackageParam> MakeXmlPackageParamsFromString(string ampersandDelimetedParams)
        {
            List<XmlPackageParam> xmlParams = new List<XmlPackageParam>();

            foreach (string s in ampersandDelimetedParams.Split('&'))
            {
                string[] s2 = s.Split(new Char[] { '=' }, 2);
                string ParamName = string.Empty;
                try
                {
                    ParamName = s2[0];
                }
                catch { }
                string ParamValue = string.Empty;
                try
                {
                    ParamValue = s2[1].ToUrlDecode();
                }
                catch { }

                if (ParamName.Length != 0)
                {
                    xmlParams.Add(new XmlPackageParam(ParamName, ParamValue));
                }
            }

            return xmlParams;
        }

        public static string RunXmlPackage(string XmlPackageName, Parser UseParser, Customer ThisCustomer, int SkinID, string RunTimeQuery, List<XmlPackageParam> RunTimeParms, bool ReplaceTokens, bool WriteExceptionMessage)
        {
            string result = string.Empty;
            try
            {
                string pn = XmlPackageName.ToLowerInvariant();
                if (!pn.EndsWith(".xml.config", StringComparison.InvariantCultureIgnoreCase))
                {
                    pn += ".xml.config";
                }

                using (XmlPackage2 p = new XmlPackage2(XmlPackageName, ThisCustomer, SkinID, RunTimeQuery, RunTimeParms))
                {
                    result = RunXmlPackage(p, UseParser, ThisCustomer, SkinID, ReplaceTokens, WriteExceptionMessage);
                }
                return result;
            }
            catch (Exception ex)
            {
                // throw the exception so it will be catched by whoever is calling this.
                return CommonLogic.GetExceptionDetail(ex, "<br/>");
            }
        }

        public static string RunXmlPackage(XmlPackage2 p, Parser UseParser, Customer ThisCustomer, int SkinID, bool ReplaceTokens, bool WriteExceptionMessage)
        {
            StringBuilder tmpS = new StringBuilder();
            try
            {
                if (p != null)
                {
                    string XmlPackageName = p.Name;
                    if (CommonLogic.ApplicationBool("DumpSQL"))
                    {
                        tmpS.Append("<p><b>XmlPackage: " + XmlPackageName + "</b></p>");
                    }
                    try
                    {
                        string s = p.TransformString();
                        if (ReplaceTokens && (p.RequiresParser || p.Version < 2.1M))
                        {
                            if (UseParser == null)
                            {
                                UseParser = new Parser(SkinID, ThisCustomer);
                            }
                            tmpS.Append(UseParser.ReplaceTokens(s));
                        }
                        else
                        {
                            tmpS.Append(s);
                        }
                    }
                    catch (Exception ex)
                    {
                        tmpS.Append("XmlPackage Exception: " + CommonLogic.GetExceptionDetail(ex, "<br/>") + ex.ToString() + "<br />");
                    }
                    if (AppLogic.AppConfigBool("XmlPackage.DumpTransform") || p.IsDebug)
                    {
                        tmpS.Append("<div>");
                        tmpS.Append("<br/><b>" + p.URL + "<br/>");
                        tmpS.Append("<textarea READONLY cols=\"80\" rows=\"50\">" + XmlCommon.XmlEncode(XmlCommon.PrettyPrintXml(p.PackageDocument.InnerXml)) + "</textarea>");
                        tmpS.Append("</div>");

                        tmpS.Append("<div>");
                        tmpS.Append("<br/><b>" + XmlPackageName + "_store.runtime.xml<br/>");
                        tmpS.Append("<textarea READONLY cols=\"80\" rows=\"50\">" + XmlCommon.XmlEncode(CommonLogic.ReadFile("images/" + XmlPackageName + "_store.runtime.xml", true)) + "</textarea>");
                        tmpS.Append("</div>");

                        tmpS.Append("<div>");
                        tmpS.Append("<br/><b>" + XmlPackageName + "_store.runtime.sql<br/>");
                        tmpS.Append("<textarea READONLY cols=\"80\" rows=\"50\">" + XmlCommon.XmlEncode(CommonLogic.ReadFile("images/" + XmlPackageName + "_store.runtime.sql", true)) + "</textarea>");
                        tmpS.Append("</div>");

                        tmpS.Append("<div>");
                        tmpS.Append("<br/><b>" + XmlPackageName + "_store.xfrm.xml<br/>");
                        tmpS.Append("<textarea READONLY cols=\"80\" rows=\"50\">" + XmlCommon.XmlEncode(CommonLogic.ReadFile("images/" + XmlPackageName + "_store.xfrm.xml", true)) + "</textarea>");
                        tmpS.Append("</div>");
                    }
                }
                else
                {
                    tmpS.Append("XmlPackage2 parameter is null");
                }
            }
            catch (Exception ex)
            {
                tmpS.Append(CommonLogic.GetExceptionDetail(ex, "<br/>"));
            }
            return tmpS.ToString();
        }

        public static string[] ReadXmlPackages(string PackageFilePrefix, int SkinID)
        {
            return ReadXmlPackages(PackageFilePrefix, SkinID, false, false);
        }

        public static string[] ReadXmlPackages(string PackageFilePrefix, int SkinID, bool isInMobile)
        {
            return ReadXmlPackages(PackageFilePrefix, SkinID, false, isInMobile);
        }

        public static string[] ReadXmlPackages(string PackageFilePrefix, int SkinID, bool isOnMiniAdminSite, bool isInMobile)
        {
            // create an array to hold the list of files
            var fArray = new List<string>();

            string sourceFolder = string.Empty;
            string mobileFolderName = CommonLogic.Application(DomainConstants.MobileFolderName).ToLowerInvariant();
            string skinFolder = "skins/skin_" + SkinID.ToString();

            if (isInMobile)
            {
                sourceFolder = ((isInMobile) ? mobileFolderName + "/" : string.Empty);
            }
            else if (isOnMiniAdminSite)
            {
                sourceFolder = ((isOnMiniAdminSite) ? "../" : string.Empty);
            }

            string sourceSkinFolder = skinFolder;
            if(isInMobile)
            {
                sourceSkinFolder = sourceFolder + skinFolder;
            }
            else if (isOnMiniAdminSite)
            {
                sourceSkinFolder = sourceFolder + skinFolder;
            }

            // check skin area:
            string SFP = CommonLogic.SafeMapPath(sourceSkinFolder + "/XmlPackages/bogus.htm").Replace("bogus.htm", string.Empty);
            fArray.AddRange(GetXmlPackages(SFP, PackageFilePrefix));

            // now check common area:
            SFP = CommonLogic.SafeMapPath(sourceFolder + "XmlPackages/bogus.htm").Replace("bogus.htm", string.Empty);
            fArray.AddRange(GetXmlPackages(SFP, PackageFilePrefix));

            if (fArray.Count != 0) { fArray.OrderBy(s => s); }

            return fArray.ToArray();
        }

        private static string[] GetXmlPackages(string folder, string prefix)
        {
            // create an array to hold the list of files
            var fArray = new List<string>();

            var dirInfo = new DirectoryInfo(folder);
            var myDir = dirInfo.GetFiles(CommonLogic.IIF(prefix.Length != 0, prefix + ".*.xml.config", "*.xml.config"));
            for (int i = 0; i < myDir.Length; i++)
            {
                fArray.Add(myDir[i].ToString().ToLowerInvariant());
            }

            return fArray.ToArray();
        }

        public static string GetCountrySelectList(string currentLocaleSetting)
        {
            string CacheName = "GetCountrySelectList" + currentLocaleSetting + "_" + CommonLogic.GetThisPageName(true);
            if (AppLogic.CachingOn)
            {
                string htmlTest = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
                if (!htmlTest.IsNullOrEmptyTrimmed()) return htmlTest;
            }

            var ds = DB.GetDS("SELECT * FROM eCommerceWebLocaleView with (NOLOCK)", true, DateTime.Now.AddHours(1));
            if (ds.Tables[0].Rows.Count == 0)
            {
                ds.Dispose();
                return string.Empty;
            }

            var tmpS = new StringBuilder(4096);

            tmpS.Append("<!-- COUNTRY SELECT LIST -->\n");
            tmpS.Append("<select size=\"1\" onChange=\"self.location='setlocale.aspx?returnURL=" + HttpContext.Current.Server.UrlEncode(CommonLogic.GetThisPageName(true) + "?" + CommonLogic.ServerVariables("QUERY_STRING")) + "&localesetting=' + document.getElementById('CountrySelectList').value\" id=\"CountrySelectList\" name=\"CountrySelectList\" class=\"CountrySelectList\">");
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                tmpS.Append("<option value=\"" + DB.RowField(row, "ShortString") + "\" " + CommonLogic.IIF(currentLocaleSetting.Equals(DB.RowField(row, "ShortString"), StringComparison.InvariantCultureIgnoreCase), " selected ", "") + ">" + DB.RowField(row, "LanguageDescription") + "</option>");
            }
            tmpS.Append("</select>");

            tmpS.Append("<!-- END COUNTRY SELECT LIST -->\n");
            ds.Dispose();

            if (CachingOn)
            {
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, tmpS.ToString(), AppLogic.CacheDurationMinutes());
            }
            return tmpS.ToString();
        }

        public static string GetCurrencySelectList(Customer ThisCustomer)
        {
            if (Currency.NumPublishedCurrencies() == 0)
            {
                return string.Empty;
            }
            string tmpS = Currency.GetSelectList("CurrencySelectList", "self.location='setcurrency.aspx?returnURL=" + HttpContext.Current.Server.UrlEncode(CommonLogic.GetThisPageName(true) + "?" + CommonLogic.ServerVariables("QUERY_STRING")) + "&currencysetting=' + document.getElementById('CurrencySelectList').value", string.Empty, ThisCustomer.CurrencyCode);
            return tmpS.ToString();
        }

        public static int SessionTimeout()
        {
            int ST = AppLogic.AppConfigUSInt("SessionTimeoutInMinutes");
            if (ST == 0)
            {
                ST = 20;
            }
            return ST;
        }

        public static int CacheDurationMinutes()
        {
            int ST = AppLogic.AppConfigUSInt("CacheDurationMinutes");
            if (ST == 0)
            {
                ST = 20;
            }
            return ST;
        }

        public static string GetUserMenu(bool IsNotRegistered, int SkinID, string m_LocaleSetting)
        {
            var tmpS = new StringBuilder(1000);
            tmpS.Append("<div id=\"userMenu\" class=\"menu\">\n");
            if (IsNotRegistered)
            {
                tmpS.Append("<a class=\"menuItem\" href=\"signin.aspx\">" + GetString("skinbase.cs.4", SkinID, m_LocaleSetting) + "</a>\n");
                tmpS.Append("<a class=\"menuItem\" href=\"account.aspx\">" + GetString("skinbase.cs.6", SkinID, m_LocaleSetting) + "</a>\n");
            }
            else
            {
                tmpS.Append("<a class=\"menuItem\" href=\"account.aspx\">" + GetString("skinbase.cs.7", SkinID, m_LocaleSetting) + "</a>\n");
                tmpS.Append("<a class=\"menuItem\" href=\"signout.aspx\">" + GetString("skinbase.cs.5", SkinID, m_LocaleSetting) + "</a>\n");
            }
            tmpS.Append("</div>\n");
            return tmpS.ToString();
        }

        public static string NoPictureImageURL(bool icon, int SkinID, string LocaleSetting)
        {
            return AppLogic.LocateImageURL("skins/skin_" + SkinID.ToString() + "/images/nopicture" + CommonLogic.IIF(icon, "icon", "") + ".gif", LocaleSetting);
        }

        // given an input image string like /skins/skin_1/images/shoppingcart.gif
        // tries to resolve it to the proper locale by:
        // /skins/skin_1/images/shoppingcart.LocaleSetting.gif first
        // /skins/skin_1/images/shoppingcart.WebConfigLocale.gif second
        // /skins/skin_1/images/shoppingcart.gif last
        public static string LocateImageURL(string ImageName, string LocaleSetting)
        {
            string CacheName = "LocateImageURL_" + ImageName + "_" + LocaleSetting;
            if (AppLogic.CachingOn)
            {
                string s = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
                if (s != null)
                {
                    return s;
                }
            }

            int i = ImageName.LastIndexOf(".");
            string url = string.Empty;
            if (i == -1)
            {
                url = ImageName; // no extension??
            }
            else
            {
                string Extension = ImageName.Substring(i);
                url = ImageName.Substring(0, i) + "." + LocaleSetting + Extension;
                if (!CommonLogic.FileExists(url))
                {
                    url = ImageName.Substring(0, i) + "." + Customer.Current.LocaleSetting + Extension;
                }
                if (!CommonLogic.FileExists(url))
                {
                    url = ImageName.Substring(0, i) + Extension;
                }
            }
            if (CachingOn)
            {
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, url, AppLogic.CacheDurationMinutes());
            }
            return url;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ImageName">Image filename with or without the extension</param>
        /// <param name="ImageType">e.g. Category, Section, Product</param>
        /// <param name="LocaleSetting">Viewing Locale</param>
        /// <returns>full path to the image</returns>
        public static string LocateImageURL(string ImageName, string ImageType, string ImgSize, string LocaleSetting)
        {
            if (CurrentContext.IsRequestingFromMobileMode(Customer.Current))
            {
                ImgSize = "mobile";
            }

            ImageName = ImageName.Trim();
            string WebConfigLocale = "." + Localization.WebConfigLocale;
            string IPath = GetImagePath(ImageType, ImgSize, true);
            if (LocaleSetting.Trim() != "") { LocaleSetting = "." + LocaleSetting; }
            string ImagePath = string.Empty;
            bool UseCache = false;

            //Used for ImageFilenameOverride
            if (ImageName.ToLower().EndsWith(".jpg") || ImageName.ToLower().EndsWith(".gif") || ImageName.ToLower().EndsWith(".png"))
            {
                ImagePath = IPath + ImageName.Replace(".", LocaleSetting + ".");
                if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) ImageFilenameCache.Add(ImagePath, "");
                if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                {
                    return (string)ImageFilenameCache[ImagePath];
                }
                else if ((!UseCache || ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") && CommonLogic.FileExists(ImagePath))
                {
                    ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName;
                    return (string)ImageFilenameCache[ImagePath];
                }
                if ((string)ImageFilenameCache[ImagePath] == "") ImageFilenameCache[ImagePath] = "0";

                if (LocaleSetting != WebConfigLocale)
                {
                    ImagePath = IPath + ImageName.Replace(".", WebConfigLocale + ".");
                    if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) ImageFilenameCache.Add(ImagePath, "");
                    if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                    {
                        return (string)ImageFilenameCache[ImagePath];
                    }
                    else if ((!UseCache || ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") && CommonLogic.FileExists(ImagePath))
                    {
                        ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName;
                        return (string)ImageFilenameCache[ImagePath];
                    }
                    if ((string)ImageFilenameCache[ImagePath] == "") { ImageFilenameCache[ImagePath] = "0"; }
                }
                ImagePath = IPath + ImageName;
                if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) { ImageFilenameCache.Add(ImagePath, ""); }
                if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                {
                    return (string)ImageFilenameCache[ImagePath];
                }
                else if ((!UseCache || ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") && CommonLogic.FileExists(ImagePath))
                {
                    ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName;
                    return (string)ImageFilenameCache[ImagePath];
                }
                if ((string)ImageFilenameCache[ImagePath] == "") { ImageFilenameCache[ImagePath] = "0"; }

                return "";
            }
            else
            {
                ImagePath = IPath + ImageName + LocaleSetting + ".jpg";
                if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) { ImageFilenameCache.Add(ImagePath, ""); }
                if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                {
                    return (string)ImageFilenameCache[ImagePath];
                }
                else if ((!UseCache || (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "")) && CommonLogic.FileExists(ImagePath))
                {
                    ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName + LocaleSetting + ".jpg";
                    return (string)ImageFilenameCache[ImagePath];
                }
                if (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") { ImageFilenameCache[ImagePath] = "0"; }

                ImagePath = IPath + ImageName + LocaleSetting + ".gif";
                if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) { ImageFilenameCache.Add(ImagePath, ""); }
                if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                {
                    return (string)ImageFilenameCache[ImagePath];
                }
                else if ((!UseCache || (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "")) && CommonLogic.FileExists(ImagePath))
                {
                    ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName + LocaleSetting + ".gif";
                    return (string)ImageFilenameCache[ImagePath];
                }
                if (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") { ImageFilenameCache[ImagePath] = "0"; }

                ImagePath = IPath + ImageName + LocaleSetting + ".png";
                if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) { ImageFilenameCache.Add(ImagePath, ""); }
                if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                {
                    return (string)ImageFilenameCache[ImagePath];
                }
                else if ((!UseCache || (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "")) && CommonLogic.FileExists(ImagePath))
                {
                    ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName + LocaleSetting + ".png";
                    return (string)ImageFilenameCache[ImagePath];
                }
                if (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") { ImageFilenameCache[ImagePath] = "0"; }

                if (LocaleSetting != WebConfigLocale)
                {
                    LocaleSetting = WebConfigLocale;
                    ImagePath = IPath + ImageName + LocaleSetting + ".jpg";
                    if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) { ImageFilenameCache.Add(ImagePath, ""); }
                    if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                    {
                        return (string)ImageFilenameCache[ImagePath];
                    }
                    else if ((!UseCache || (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "")) && CommonLogic.FileExists(ImagePath))
                    {
                        ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName + LocaleSetting + ".jpg";
                        return (string)ImageFilenameCache[ImagePath];
                    }
                    if (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") { ImageFilenameCache[ImagePath] = "0"; }

                    ImagePath = IPath + ImageName + LocaleSetting + ".gif";
                    if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) { ImageFilenameCache.Add(ImagePath, ""); }
                    if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                    {
                        return (string)ImageFilenameCache[ImagePath];
                    }
                    else if ((!UseCache || (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "")) && CommonLogic.FileExists(ImagePath))
                    {
                        ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName + LocaleSetting + ".gif";
                        return (string)ImageFilenameCache[ImagePath];
                    }
                    if (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") { ImageFilenameCache[ImagePath] = "0"; }

                    ImagePath = IPath + ImageName + LocaleSetting + ".png";
                    if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) { ImageFilenameCache.Add(ImagePath, ""); }
                    if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                    {
                        return (string)ImageFilenameCache[ImagePath];
                    }
                    else if ((!UseCache || (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "")) && CommonLogic.FileExists(ImagePath))
                    {
                        ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName + LocaleSetting + ".png";
                        return (string)ImageFilenameCache[ImagePath];
                    }
                    if (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") { ImageFilenameCache[ImagePath] = "0"; }
                }

                ImagePath = IPath + ImageName + ".jpg";
                if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) { ImageFilenameCache.Add(ImagePath, ""); }
                if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                {
                    return (string)ImageFilenameCache[ImagePath];
                }
                else if ((!UseCache || (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "")) && CommonLogic.FileExists(ImagePath))
                {
                    ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName + ".jpg";
                    return (string)ImageFilenameCache[ImagePath];
                }
                if (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") ImageFilenameCache[ImagePath] = "0";

                ImagePath = IPath + ImageName + ".gif";
                if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) { ImageFilenameCache.Add(ImagePath, ""); }
                if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                {
                    return (string)ImageFilenameCache[ImagePath];
                }
                else if ((!UseCache || (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "")) && CommonLogic.FileExists(ImagePath))
                {
                    ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName + ".gif";
                    return (string)ImageFilenameCache[ImagePath];
                }
                if (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") { ImageFilenameCache[ImagePath] = "0"; }

                ImagePath = IPath + ImageName + ".png";
                if (UseCache && !ImageFilenameCache.ContainsKey(ImagePath)) { ImageFilenameCache.Add(ImagePath, ""); }
                if (UseCache && ((string)ImageFilenameCache[ImagePath]).Length > 1)
                {
                    return (string)ImageFilenameCache[ImagePath];
                }
                else if ((!UseCache || (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "")) && CommonLogic.FileExists(ImagePath))
                {
                    ImageFilenameCache[ImagePath] = GetImagePath(ImageType, ImgSize, false) + ImageName + ".png";
                    return (string)ImageFilenameCache[ImagePath];
                }
                if (ImageFilenameCache[ImagePath] == null || (string)ImageFilenameCache[ImagePath] == "") { ImageFilenameCache[ImagePath] = "0"; }
                return "";
            }
        }

        public static string LocateImageURL(string ImageName)
        {
            return AppLogic.LocateImageURL(ImageName, Thread.CurrentThread.CurrentUICulture.Name);
        }

        public static string WriteTabbedContents(string tabDivName, int selectedTabIdx, bool includeTabJSDriverFile, string[] names, string[] values)
        {
            StringBuilder tmpS = new StringBuilder(10000);
            if (includeTabJSDriverFile)
            {
                tmpS.Append(CommonLogic.ReadFile("jscripts/tabs.js", true));
            }
            tmpS.Append("<div class=\"tab-container\" id=\"" + tabDivName + "\" width=\"100%\">\n");
            tmpS.Append("<ul class=\"tabs\">\n");
            for (int i = names.GetLowerBound(0); i <= names.GetUpperBound(0); i++)
            {
                tmpS.Append("<li><a href=\"#\" onClick=\"return showPane('" + tabDivName + "_pane" + (i + 1).ToString() + "', this)\" id=\"" + tabDivName + "_tab" + (i + 1).ToString() + "\">" + names[i] + "</a></li>\n");
            }
            tmpS.Append("</ul>\n");
            tmpS.Append("<div class=\"tab-panes\" width=\"100%\">\n");
            for (int i = names.GetLowerBound(0); i <= names.GetUpperBound(0); i++)
            {
                tmpS.Append("<div id=\"" + tabDivName + "_pane" + (i + 1).ToString() + "\" width=\"100%\" style=\"overflow:auto;height:200px;\">\n");
                tmpS.Append(values[i]);
                tmpS.Append("</div>\n");
            }
            tmpS.Append("</div>\n");
            tmpS.Append("</div>\n");
            tmpS.Append("<script language=\"JavaScript1.3\">\nsetupPanes('" + tabDivName + "', '" + tabDivName + "_tab" + CommonLogic.IIF(selectedTabIdx == 0, "1", selectedTabIdx.ToString()) + "');\n</script>\n");
            return tmpS.ToString();
        }

        public static string GetCartContinueShoppingURL(int SkinID, string LocaleSetting)
        {
            string tmpS = AppLogic.AppConfig("ContinueShoppingURL"); // this overrides all!
            if (tmpS.Length == 0)
            {
                // no appconfig set, so try to do something reasonable:
                if (CommonLogic.QueryStringUSInt("ResetLinkback") == 1)
                {
                    tmpS = "default.aspx";
                }
                else
                {
                    tmpS = "default.aspx";
                }
            }
            return tmpS;
        }

        // handles login "transformation" from one customer on the site to another, moving
        // cart items, etc...as required. This is a fairly complicated routine to get right ;)
        // this does NOT alter any session/cookie data...you should do that before/after this call
        // don't migrate their shipping info...their "old address book should take priority"
        public static void ExecuteSigninLogic(string CurrentCustomerID, string CurrentContactCode, string NewCustomerID, string ShipToCode, string NewContactCode)
        {
            string CurrentCustomerOrderNotes = String.Empty;
            string CurrentOrderOptions = String.Empty;

            decimal ItemsInCartNow = ShoppingCart.NumItems(CurrentCustomerID, CartTypeEnum.ShoppingCart, CurrentContactCode);

            // but not wish list, gift registry or recurring items!
            if ((ItemsInCartNow > 0 && AppLogic.AppConfigBool("PreserveActiveCartOnSignin")) || AppLogic.AppConfigBool("ClearOldCartOnSignin"))
            {
                // if preserve is on, force delete of old cart even if not set at appconfig level, since we are replacing it with the active cart:
                InterpriseHelper.ClearCart(CartTypeEnum.ShoppingCart, NewCustomerID.ToString(), NewContactCode);
            }

            if (ItemsInCartNow <= 0 && !AppLogic.AppConfigBool("PreserveActiveCartOnSignin")) return;

            if (CurrentCustomerID.Length == 0) return;

            InterpriseHelper.UpdateAnonymousCart(CartTypeEnum.ShoppingCart, CurrentCustomerID, NewCustomerID, ShipToCode, NewContactCode);
        }

        public static void SendOrderEMail(Customer activeCustomer, InterpriseShoppingCart cart, string OrderNumber, bool IsRecurring, string PaymentMethod, bool NotifyStoreAdmin, bool multipleAttachment)
        {
            bool UseLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            string StoreName = AppLogic.AppConfig("StoreName");
            string MailServer = AppLogic.AppConfig("MailMe_Server");

            string OrdPM = string.Empty;
            string SubjectReceipt = string.Empty;
            string[] emailacctinfo = InterpriseHelper.GetStoreEmailAccountInfo();

            if (!string.IsNullOrEmpty(emailacctinfo[0]))
            {
                OrdPM = AppLogic.CleanPaymentMethod(PaymentMethod);
                if (UseLiveTransactions)
                {
                    SubjectReceipt = string.Format(GetString("common.cs.1", activeCustomer.SkinID, activeCustomer.LocaleSetting), StoreName);
                }
                else
                {
                    SubjectReceipt = string.Format(GetString("common.cs.2", activeCustomer.SkinID, activeCustomer.LocaleSetting), StoreName);
                }
                if (OrdPM == AppLogic.ro_PMRequestQuote)
                {
                    SubjectReceipt += GetString("common.cs.3", activeCustomer.SkinID, activeCustomer.LocaleSetting);
                }
                string SubjectNotification = string.Empty;
                if (UseLiveTransactions)
                {
                    SubjectNotification = string.Format(GetString("common.cs.4", activeCustomer.SkinID, activeCustomer.LocaleSetting), StoreName);
                }
                else
                {
                    SubjectNotification = string.Format(GetString("common.cs.5", activeCustomer.SkinID, activeCustomer.LocaleSetting), StoreName);
                }
                if (OrdPM == AppLogic.ro_PMRequestQuote)
                {
                    SubjectNotification += GetString("common.cs.3", activeCustomer.SkinID, activeCustomer.LocaleSetting);
                }

                if (IsRecurring)
                {
                    SubjectReceipt += GetString("common.cs.6", activeCustomer.SkinID, activeCustomer.LocaleSetting);
                }

                if (NotifyStoreAdmin)
                {
                    // send E-Mail notice to store admin:
                    try
                    {
                        if (AppLogic.AppConfig("GotOrderEMailTo").Length != 0)
                        {
                            string SendToList = AppLogic.AppConfig("GotOrderEMailTo").Replace(",", ";");
                            if (SendToList.IndexOf(';') != -1)
                            {
                                foreach (string s in SendToList.Split(';'))
                                {
                                    AppLogic.SendMailRequest(SubjectNotification, AppLogic.AdminNotification(OrderNumber, activeCustomer.SkinID) + AppLogic.AppConfig("MailFooter"), true, emailacctinfo[0], emailacctinfo[1], s.Trim(), s.Trim(), "");
                                }
                            }
                            else
                            {
                                AppLogic.SendMailRequest(SubjectNotification, AppLogic.AdminNotification(OrderNumber, activeCustomer.SkinID) + AppLogic.AppConfig("MailFooter"), true, emailacctinfo[0], emailacctinfo[1], SendToList, SendToList, "");
                            }
                        }
                    }
                    catch { }
                }

                //  now send customer e-mails:
                bool OKToSend = false;
                if (!CommonLogic.IsStringNullOrEmpty(activeCustomer.EMail))
                {
                    if (IsRecurring)
                    {
                        if (AppLogic.AppConfigBool("Recurring.SendOrderEMailToCustomer"))
                        {
                            OKToSend = true;
                        }
                    }
                    else
                    {
                        if (AppLogic.AppConfigBool("SendOrderEMailToCustomer"))
                        {
                            OKToSend = true;
                        }
                    }
                }
                if (OKToSend)
                {
                    try
                    {
                        // NOTE: we changed this to ALWAYS send the receipt:
                        try
                        {
                            string strMessageBody = Receipt(activeCustomer, OrderNumber);
                            // if the message body has an exception then don't send the email
                            if (!string.IsNullOrEmpty(strMessageBody) && strMessageBody.IndexOf("Exception=") < 0)
                            {
                                AppLogic.SendMailRequest(SubjectReceipt, strMessageBody, true, emailacctinfo[0], emailacctinfo[1], activeCustomer.EMail, activeCustomer.EMail, string.Empty, string.Empty, OrderNumber, true, multipleAttachment);
                            }
                            else
                            {
                                throw new Exception(strMessageBody);
                            }
                        }
                        catch { throw; }
                    }
                    catch { throw; }
                }
            }
        }

        /// <summary>
        /// Use to send email only to admin. This is used by Request Quote and Purchase Order where we do not need to notify the customer.
        /// </summary>
        /// <param name="activeCustomer">Current login customer credentials.</param>
        /// <param name="cart">Information on items on the cart.</param>
        /// <param name="OrderNumber">Sales Order or Quote transaction ID.</param>
        /// <param name="IsRecurring">Determine if order is recurring.</param>
        /// <param name="PaymentMethod">Used payment type.</param>
        /// <param name="multipleAttachment">If order is multi ship.</param>
        public static void SendOrderEMail(Customer activeCustomer, InterpriseShoppingCart cart, string OrderNumber, bool IsRecurring, string PaymentMethod, bool multipleAttachment)
        {
            bool UseLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            string StoreName = AppLogic.AppConfig("StoreName");
            string MailServer = AppLogic.AppConfig("MailMe_Server");

            string OrdPM = string.Empty;
            string SubjectReceipt = string.Empty;
            string[] emailacctinfo = InterpriseHelper.GetStoreEmailAccountInfo();

            if (!string.IsNullOrEmpty(emailacctinfo[0]))
            {
                OrdPM = AppLogic.CleanPaymentMethod(PaymentMethod);
                if (UseLiveTransactions)
                {
                    SubjectReceipt = string.Format(GetString("common.cs.1", activeCustomer.SkinID, activeCustomer.LocaleSetting), StoreName);
                }
                else
                {
                    SubjectReceipt = string.Format(GetString("common.cs.2", activeCustomer.SkinID, activeCustomer.LocaleSetting), StoreName);
                }
                if (OrdPM == AppLogic.ro_PMRequestQuote)
                {
                    SubjectReceipt += GetString("common.cs.3", activeCustomer.SkinID, activeCustomer.LocaleSetting);
                }
                string SubjectNotification = string.Empty;
                if (UseLiveTransactions)
                {
                    SubjectNotification = string.Format(GetString("common.cs.4", activeCustomer.SkinID, activeCustomer.LocaleSetting), StoreName);
                }
                else
                {
                    SubjectNotification = string.Format(GetString("common.cs.5", activeCustomer.SkinID, activeCustomer.LocaleSetting), StoreName);
                }
                if (OrdPM == AppLogic.ro_PMRequestQuote)
                {
                    SubjectNotification += GetString("common.cs.3", activeCustomer.SkinID, activeCustomer.LocaleSetting);
                }

                if (IsRecurring)
                {
                    SubjectReceipt += GetString("common.cs.6", activeCustomer.SkinID, activeCustomer.LocaleSetting);
                }
                // send E-Mail notice to store admin:
                try
                {
                    if (AppLogic.AppConfig("GotOrderEMailTo").Length != 0)
                    {
                        string SendToList = AppLogic.AppConfig("GotOrderEMailTo").Replace(",", ";");
                        if (SendToList.IndexOf(';') != -1)
                        {
                            foreach (string s in SendToList.Split(';'))
                            {
                                AppLogic.SendMailRequest(SubjectNotification, AppLogic.AdminNotification(OrderNumber, activeCustomer.SkinID) + AppLogic.AppConfig("MailFooter"), true, emailacctinfo[0], emailacctinfo[1], s.Trim(), s.Trim(), "");
                            }
                        }
                        else
                        {
                            AppLogic.SendMailRequest(SubjectNotification, AppLogic.AdminNotification(OrderNumber, activeCustomer.SkinID) + AppLogic.AppConfig("MailFooter"), true, emailacctinfo[0], emailacctinfo[1], SendToList, SendToList, "");
                        }
                    }
                }
                catch { }
            }
        }

        static string AdminNotification(string OrderNumber, int SkinID)
        {
            string result = string.Empty;
            try
            {
                string PackageName = AppLogic.AppConfig("XmlPackage.NewOrderAdminNotification");
                if (PackageName.Length != 0)
                {
                    XmlPackage2 p = new XmlPackage2(PackageName, null, SkinID, String.Empty, AppLogic.MakeXmlPackageParamsFromString("ordernumber=" + OrderNumber));
                    result = p.TransformString();
                }
            }
            catch { }
            return result;
        }

        public static string ReplaceTokens(string S, int SkinID, Customer ThisCustomer, System.Collections.Generic.Dictionary<string, EntityHelper> EntityHelpers, Parser useParser)
        {
            if (S.IndexOf("(!") == -1)
            {
                return S; // no tokensre!
            }
            if (useParser == null)
            {
                useParser = new Parser(EntityHelpers, SkinID, ThisCustomer);
            }
            return useParser.ReplaceTokens(S);
        }

        public static bool IsValidAffiliate(string AffiliateID)
        {
            return (DB.GetSqlN("select count(SalesRepGroupCode) as N from CustomerSalesRep with (NOLOCK) where IsActive=1 and SalesRepGroupCode=" + DB.SQuote(AffiliateID)) != 0);
        }

        public static bool IsOnlineAffiliate(string AffiliateID)
        {
            bool tmp = false;
            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, "select IsWebAccess from CustomerSalesRep with (NOLOCK) where SalesRepGroupCode=" + DB.SQuote(AffiliateID)))
                {
                    if (rs.Read())
                    {
                        tmp = DB.RSFieldBool(rs, "IsWebAccess");
                    }
                }
            }

            return tmp;
        }

        public static string GetProductDescription(string ProductID, string LocaleSetting)
        {
            string tmpS = string.Empty;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, "select ItemDescription from InventoryItemDescription with (NOLOCK) where ItemCode=" + ProductID.ToString()))
                {
                    if (rs.Read())
                    {
                        tmpS = DB.RSFieldByLocale(rs, "Description", LocaleSetting);
                    }
                }
            }

            if (AppLogic.ReplaceImageURLFromAssetMgr)
            {
                tmpS = tmpS.Replace("../images", "images");
            }
            return tmpS;
        }

        public static string GetProductSummary(string ProductID, string LocaleSetting)
        {
            string tmpS = string.Empty;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, "SELECT Summary from InventoryItemWebOptionDescription with (NOLOCK) where ItemCode=" + ProductID.ToString() +
                                      " AND WebSiteCode=" + DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode)))
                {
                    if (rs.Read())
                    {
                        tmpS = DB.RSFieldByLocale(rs, "Summary", LocaleSetting);
                    }
                }
            }

            return tmpS;
        }

        public static string GetCAVV(string OrderNumber)
        {
            string tmpS = string.Empty;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "Select CardinalAuthenticateResult from Orders with (NOLOCK) where OrderNumber=" + OrderNumber.ToString()))
                {
                    if (rs.Read())
                    {
                        tmpS = CommonLogic.ExtractToken(DB.RSField(rs, "CardinalAuthenticateResult"), "<Cavv>", "</Cavv>");
                    }
                }
            }

            return tmpS;
        }

        public static void ReloadStringResources(string LocaleSetting)
        {
            //DB.ExecuteSQL(string.Format("delete from EcommerceStoreStringResource where LocaleSetting={0} AND WebsiteCode = {1}", DB.SQuote(LocaleSetting), DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode)));
            DB.ExecuteSQL(string.Format("delete from EcommerceStringResource where LocaleSetting={0} AND WebsiteCode = {1}", DB.SQuote(LocaleSetting), DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode)));
            LoadStringResourcesFromDB(true);
        }

        public static void LoadStringResourcesFromDB(bool TryToReload)
        {
            // load all strings into cache:            
            StringResourceTable = StringResources.GetAll();
        }

        public static string GetStockHints(string ItemCode)
        {
            string CacheName = "GetStockHints_" + ItemCode.ToString();
            if (AppLogic.CachingOn)
            {
                string htmlTest = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
                if (!htmlTest.IsNullOrEmptyTrimmed()) return htmlTest;
            }

            var tmpS = new StringBuilder(10000);
            string matrixgroup = string.Empty;
            string matrixitemcode = string.Empty;

            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var datareader = DB.GetRSFormat(con, "SELECT DISTINCT dbo.InventoryItem.ItemCode, dbo.InventoryItem.ItemName, dbo.InventoryMatrixItem.MatrixItemName, dbo.InventoryItem.ItemType,dbo.InventoryMatrixItem.MatrixItemCode FROM dbo.InventoryItem with (NOLOCK) INNER JOIN dbo.InventoryMatrixItem with (NOLOCK) ON dbo.InventoryItem.ItemCode = dbo.InventoryMatrixItem.ItemCode WHERE dbo.InventoryItem.ItemCode = {0}", DB.SQuote(ItemCode.ToString())))
                {
                    if (datareader.Read())
                    {
                        matrixgroup = DB.RSField(datareader, "ItemType");
                        if (matrixgroup == "Matrix Group")
                        {
                            matrixitemcode = DB.RSField(datareader, "MatrixItemCode");
                            ItemCode = matrixitemcode.ToString();
                        }
                    }
                }
            }

            bool ForStocking = false;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "SELECT CASE WHEN COUNT(ItemCode) > 0 THEN 1 ELSE 0 END AS ForStocking FROM InventoryItem with (NOLOCK) WHERE ItemType IN ('Stock', 'Kit','Matrix Group', 'Assembly') AND ItemCode = {0}", DB.SQuote(ItemCode.ToString())))
                {
                    if (rs.Read())
                    {
                        ForStocking = DB.RSFieldBool(rs, "ForStocking");
                        if (!ForStocking)
                        {
                            tmpS.Append(string.Empty);
                        }
                    }
                }
            }

            if (ForStocking)
            {

                using (var con = DB.NewSqlConnection())
                {
                    con.Open();
                    using (var rs = DB.GetRSFormat(con, "Select sum(UnitsInStock) as UnitsInStock from InventoryStockTotal with (NOLOCK) where ItemCode = {0}", DB.SQuote(ItemCode.ToString())))
                    {
                        if (rs.Read())
                        {
                            decimal iVal = DB.RSFieldDecimal(rs, "UnitsInStock");
                            tmpS.Append("<div align=\"left\">");
                            tmpS.Append("<img border=\"0\" id=\"imgStockHint\" src=\"images/" + CommonLogic.IIF(iVal > 0, "instock", "outofstock") + ".gif\">");
                            tmpS.Append("</div>");
                        }
                    }
                }

            }

            if (AppLogic.CachingOn)
            {
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, tmpS.ToString(), AppLogic.CacheDurationMinutes());
            }
            return tmpS.ToString();
        }

        public static string GetProductManufacturerID(string ProductID)
        {
            string tmp = string.Empty;
            if (ProductID.Length != 0)
            {
                using (var con = DB.NewSqlConnection())
                {
                    con.Open();
                    using (var rs = DB.GetRSFormat(con, "select ManufacturerID from ProductManufacturer with (NOLOCK) where ProductID=" + ProductID.ToString()))
                    {
                        if (rs.Read())
                        {
                            tmp = DB.RSField(rs, "ManufacturerID");
                        }
                    }
                }
            }
            return tmp;
        }

        public static string GetProductsFirstVariantID(string ProductID)
        {
            string tmp = string.Empty;
            if (ProductID.Length != 0)
            {
                using (var con = DB.NewSqlConnection())
                {
                    con.Open();
                    using (var rs = DB.GetRSFormat(con, "select min(MatrixItemCode) as VID from InventoryMatrixItem A with (NOLOCK) INNER JOIN InventoryItem B with (NOLOCK) ON A.ItemCode = B.ItemCode" +
                                          " INNER JOIN InventoryItemWebOption C with (NOLOCK) ON B.ItemCode = C.ItemCode and C.Published=1 " +
                                          " where Status='A' and Selected = 1 and B.ItemCode=" + DB.SQuote(ProductID.ToString()) + " AND C.WebSiteCode=" + DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode)))
                    {
                        if (rs.Read())
                        {
                            tmp = DB.RSField(rs, "VID");
                        }
                    }
                }
            }
            return tmp;
        }

        public static string GetJSPopupRoutines()
        {
            var tmpS = new StringBuilder(2500);
            tmpS.Append("<script type=\"text/javascript\" Language=\"JavaScript\">\n");
            tmpS.Append("function popupwh(title,url,w,h)\n");
            tmpS.Append("	{\n");
            tmpS.Append("	window.open('popup.aspx?title=' + title + '&src=' + url,'Popup" + CommonLogic.GetRandomNumber(1, 100000).ToString() + "','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=' + w + ',height=' + h + ',left=0,top=0');\n");
            tmpS.Append("	return (true);\n");
            tmpS.Append("	}\n");
            tmpS.Append("function popuptopicwh(title,topic,w,h,scrollbars)\n");
            tmpS.Append("	{\n");
            tmpS.Append("	window.open('popup.aspx?title=' + title + '&topic=' + topic,'Popup" + CommonLogic.GetRandomNumber(1, 100000).ToString() + "','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scrollbars + ',resizable=no,copyhistory=no,width=' + w + ',height=' + h + ',left=0,top=0');\n");
            tmpS.Append("	return (true);\n");
            tmpS.Append("	}\n");
            tmpS.Append("function popuporderoptionwh(title,id,w,h,scrollbars)\n");
            tmpS.Append("	{\n");
            tmpS.Append("	window.open('popup.aspx?title=' + title + '&orderoptionid=' + id,'Popup" + CommonLogic.GetRandomNumber(1, 100000).ToString() + "','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scrollbars + ',resizable=no,copyhistory=no,width=' + w + ',height=' + h + ',left=0,top=0');\n");
            tmpS.Append("	return (true);\n");
            tmpS.Append("	}\n");
            tmpS.Append("function popupkitgroupwh(title,kitgroupid,w,h,scrollbars)\n");
            tmpS.Append("	{\n");
            tmpS.Append("	window.open('popup.aspx?title=' + title + '&kitgroupid=' + kitgroupid,'Popup" + CommonLogic.GetRandomNumber(1, 100000).ToString() + "','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scrollbars + ',resizable=no,copyhistory=no,width=' + w + ',height=' + h + ',left=0,top=0');\n");
            tmpS.Append("	return (true);\n");
            tmpS.Append("	}\n");
            tmpS.Append("function popupkititemwh(title,kititemid,w,h,scrollbars)\n");
            tmpS.Append("	{\n");
            tmpS.Append("	window.open('popup.aspx?title=' + title + '&kititemid=' + kititemid,'Popup" + CommonLogic.GetRandomNumber(1, 100000).ToString() + "','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scrollbars + ',resizable=no,copyhistory=no,width=' + w + ',height=' + h + ',left=0,top=0');\n");
            tmpS.Append("	return (true);\n");
            tmpS.Append("	}\n");
            tmpS.Append("function popup(title,url)\n");
            tmpS.Append("	{\n");
            tmpS.Append("	popupwh(title,url,600,375);\n");
            tmpS.Append("	return (true);\n");
            tmpS.Append("	}\n");
            tmpS.Append("function popuptopic(title,topic,scrollbars)\n");
            tmpS.Append("	{\n");
            tmpS.Append("	popuptopicwh(title,topic,600,375,scrollbars);\n");
            tmpS.Append("	return (true);\n");
            tmpS.Append("	}\n");
            tmpS.Append("</script>\n");
            return tmpS.ToString();
        }

        public static bool IsAKit(string ProductID)
        {
            bool tmpS = false;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "select case ItemType when 'Kit' then 1 else 0 end as IsAKit from InventoryItem with (NOLOCK) where ItemCode= {0}", DB.SQuote(ProductID.ToString())))
                {
                    if (rs.Read())
                    {
                        tmpS = DB.RSFieldBool(rs, "IsAKit");
                    }
                }
            }
            return tmpS;
        }

        public static string GetStoreHTTPLocation(bool TryToUseSSL)
        {
            string[] ScriptPathItems = CommonLogic.ServerVariables("SCRIPT_NAME").Split('/');
            string ScriptLocation = string.Empty;
            for (int i = 0; i < ScriptPathItems.GetUpperBound(0); i++)
            {
                if (ScriptPathItems[i].ToUpperInvariant() != AppLogic.GetAdminDir().ToUpperInvariant())
                {
                    ScriptLocation += ScriptPathItems[i] + "/";
                }
            }
            if (ScriptLocation.Length == 0)
            {
                ScriptLocation = "/";
            }
            if (!ScriptLocation.EndsWith("/"))
            {
                ScriptLocation = "/";
            }
            // ScriptLocation should now be everything after server name, including trailing "/", e.g. "/netstore/" or "/"
            string s = "http://" + CommonLogic.ServerVariables("HTTP_HOST") + ScriptLocation;
            if (TryToUseSSL && AppLogic.UseSSL() && AppLogic.OnLiveServer())
            {
                if (AppLogic.AppConfig("SharedSSLLocation").Length == 0)
                {
                    s = s.Replace("http:/", "https:/");
                    if (AppLogic.RedirectLiveToWWW())
                    {
                        if (s.IndexOf("https://www") == -1)
                        {
                            s = s.Replace("https://", "https://www.");
                        }
                        s = s.Replace("www.www", "www"); // safety check
                    }
                }
                else
                {
                    s = AppLogic.AppConfig("SharedSSLLocation") + ScriptLocation;
                }
            }
            return s;
        }

        public static bool CustomerLevelAllowsPO(string CustomerLevelID)
        {
            bool tmpS = false;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "Select LevelAllowsPO from CustomerLevel  with (NOLOCK) where CustomerLevelID=" + CustomerLevelID.ToString()))
                {
                    if (rs.Read())
                    {
                        tmpS = DB.RSFieldBool(rs, "LevelAllowsPO");
                    }
                }
            }
            return tmpS;
        }

        public static bool OrderHasDownloadComponents(string OrderNumber)
        {
            return DB.GetSqlN("SELECT COUNT(*) AS N FROM CustomerSalesOrderDetail with (NOLOCK) WHERE ItemType = 'Electronic Download' AND SalesOrderCode=" + DB.SQuote(OrderNumber)) != 0;
        }

        public static bool OrderHasServiceComponents(string OrderNumber)
        {
            return DB.GetSqlN("SELECT COUNT(*) AS N FROM CustomerSalesOrderDetail with (NOLOCK) WHERE ItemType = 'Service' AND SalesOrderCode=" + DB.SQuote(OrderNumber)) != 0;
        }

        public static bool OrderHasShippableComponents(string OrderNumber)
        {
            return DB.GetSqlN("SELECT COUNT(*) AS N FROM CustomerSalesOrderDetail with (NOLOCK) WHERE ItemType NOT IN ('Electronic Download', 'Service') AND SalesOrderCode=" + DB.SQuote(OrderNumber)) != 0;
        }

        public static bool ReferrerOKForSubmit()
        {
            return true;
        }

        public static string GetNewsBoxExpanded(bool LinkHeadline, bool ShowCopy, int showNum, bool IncludeFrame, bool useCache, string teaser, int SkinID, string LocaleSetting)
        {
            string CacheName = "GetNewsBoxExpanded_" + showNum.ToString() + "_" + teaser + "_" + SkinID.ToString() + "_" + LocaleSetting;
            if (AppLogic.CachingOn && useCache)
            {
                string htmlTest = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
                if (!htmlTest.IsNullOrEmptyTrimmed()) return htmlTest;
            }

            var tmpS = new StringBuilder(10000);
            string getAllNewsForThisWebsiteQuery =
            string.Format(
                "exec EcommerceGetWebNews @WebsiteCode = {0}, @LanguageCode = {1}, @CurrentDate = {2}",
                DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                DB.SQuote(Customer.Current.LanguageCode),
                DB.SQuote(Localization.ToDBDateTimeString(DateTime.Now))
            );

            var ds = DB.GetDS(getAllNewsForThisWebsiteQuery, AppLogic.CachingOn, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()));
            if (ds.Tables[0].Rows.Count > 0)
            {
                if (IncludeFrame)
                {
                    tmpS.Append("<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border=\"0\" style=\"border-style: solid; border-width: 0px; border-color: #" + AppLogic.AppConfig("HeaderBGColor") + "\">\n");
                    tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
                    tmpS.Append("<a href=\"news.aspx\"><img src=\"" + AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/newsexpanded.gif") + "\" border=\"0\" /></a><br />");
                    tmpS.Append("<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" style=\"" + AppLogic.AppConfig("BoxFrameStyle") + "\">\n");
                    tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
                }

                tmpS.Append("<p><b>" + teaser + "</b></p>\n");
                tmpS.Append("<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border=\"0\">\n");
                int i = 1;
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (i > showNum)
                    {
                        tmpS.Append("<tr><td colspan=\"2\"><hr size=\"1\" color=\"#" + AppLogic.AppConfig("MediumCellColor") + "\"/><a href=\"news.aspx\">more...</a></td></tr>");
                        break;
                    }
                    if (i > 1)
                    {
                        tmpS.Append("<tr><td colspan=\"2\"><hr size=\"1\" color=\"#" + AppLogic.AppConfig("MediumCellColor") + "\"/></td></tr>");
                    }
                    tmpS.Append("<tr>");
                    tmpS.Append("<td width=\"15%\" align=\"left\" valign=\"top\">\n");
                    tmpS.Append("<b>" + Localization.ToNativeShortDateString(DB.RowFieldDateTime(row, "DateCreated")) + "</br>");
                    tmpS.Append("</td>");
                    tmpS.Append("<td align=\"left\" valign=\"top\">\n");
                    string Hdl = DB.RowField(row, "Headline");
                    if (Hdl.Length == 0)
                    {
                        Hdl = CommonLogic.Ellipses(DB.RowField(row, "NewsContent"), 50, true);
                    }
                    tmpS.Append("<div align=\"left\">");
                    if (LinkHeadline)
                    {
                        tmpS.Append("<a href=\"news.aspx?showarticle=" + DB.RowField(row, "Counter") + "\">");
                    }
                    tmpS.Append("<b>");
                    tmpS.Append(Hdl);
                    tmpS.Append("</b>");
                    if (LinkHeadline)
                    {
                        tmpS.Append("</a>");
                    }
                    tmpS.Append("</div>");
                    if (ShowCopy)
                    {
                        tmpS.Append("<div align=\"left\"><br/>" + HttpContext.Current.Server.HtmlDecode(DB.RowField(row, "NewsContent")) + "</div>");
                    }
                    tmpS.Append("</td>");
                    tmpS.Append("</tr>");
                    i++;
                }
                tmpS.Append("</table>\n");
                ds.Dispose();

                if (IncludeFrame)
                {
                    tmpS.Append("</td></tr>\n");
                    tmpS.Append("</table>\n");
                    tmpS.Append("</td></tr>\n");
                    tmpS.Append("</table>\n");
                }
            }

            if (CachingOn && useCache)
            {
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, tmpS.ToString(), AppLogic.CacheDurationMinutes());
            }
            return tmpS.ToString();
        }

        public static string GetNewsSummary(int ShowNum)
        {
            string CacheName = "GetNewsSummary_" + ShowNum.ToString();
            if (AppLogic.CachingOn)
            {
                string Menu = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
                if (!string.IsNullOrEmpty(Menu))
                {
                    if (CommonLogic.ApplicationBool("DumpSQL"))
                    {
                        HttpContext.Current.Response.Write("Cache Hit Found!<br />\n");
                    }
                    return Menu;
                }
            }

            var tmpS = new StringBuilder(4096);

            string getAllNewsForThisWebsiteQuery =
            string.Format(
                "exec EcommerceGetWebNews @WebsiteCode = {0}, @LanguageCode = {1}, @CurrentDate = {2}",
                DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                DB.SQuote(Customer.Current.LanguageCode),
                DB.SQuote(Localization.ToDBDateTimeString(DateTime.Now))
            );

            bool anyFound = false;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, getAllNewsForThisWebsiteQuery))
                {
                    tmpS.Append("			<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n");
                    int i = 1;
                    while (rs.Read() && i <= ShowNum)
                    {
                        string Hdl = DB.RSFieldByLocale(rs, "Headline", Thread.CurrentThread.CurrentUICulture.Name);
                        if (Hdl.Length == 0)
                        {
                            Hdl = CommonLogic.Ellipses(DB.RSFieldByLocale(rs, "NewsContent", Thread.CurrentThread.CurrentUICulture.Name), 50, true);
                        }
                        tmpS.Append("				<tr><td valign=\"top\"><img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_(!SKINID!)/images/news.gif") + "\" hspace=\"10\" /></td><td><a class=\"NewsItem\" href=\"news.aspx?showarticle=" + DB.RSFieldInt(rs, "Counter").ToString() + "\">" + Hdl + "</a></td></tr>\n");
                        tmpS.Append("				<tr><td height=\"5\"></td></tr>\n");
                        anyFound = true;
                        i++;
                    }
                }
            }

            if (!anyFound)
            {
                tmpS.Append("				<tr><td valign=\"top\"><img align=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/skin_(!SKINID!)/images/newsnon.gif") + "\" hspace=\"10\" /></td><td><font class=\"NewsItem\">No News Items</font></td></tr>\n");
                tmpS.Append("				<tr><td height=\"5\"></td></tr>\n");
            }
            tmpS.Append("			</table>\n");

            if (CachingOn)
            {
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, tmpS.ToString(), AppLogic.CacheDurationMinutes());
            }
            return tmpS.ToString();
        }

        public static int GetNumSlides(string inDir)
        {
            string tPath = inDir;
            if (inDir.IndexOf(":") == -1 && inDir.IndexOf("\\\\") == -1)
            {
                tPath = CommonLogic.SafeMapPath(inDir);
            }
            bool anyFound = false;
            for (int i = 1; i <= AppLogic.AppConfigUSInt("MaxSlides"); i++)
            {
                if (!CommonLogic.FileExists(tPath + "slide" + i.ToString().PadLeft(2, '0') + ".jpg"))
                {
                    return i - 1;
                }
                else
                {
                    anyFound = true;
                }
            }
            return CommonLogic.IIF(anyFound, AppLogic.AppConfigUSInt("MaxSlides"), 0);
        }

        public static string GetGalleryTable(int SkinID, string LocaleSetting)
        {
            string CacheName = "GetGalleryTable_" + SkinID.ToString() + "_" + LocaleSetting;
            if (AppLogic.CachingOn)
            {
                string CacheData = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
                if (!string.IsNullOrEmpty(CacheData))
                {
                    if (CommonLogic.ApplicationBool("DumpSQL"))
                    {
                        HttpContext.Current.Response.Write("Cache Hit Found!<br />\n");
                    }
                    return CacheData;
                }
            }

            var tmpS = new StringBuilder(10000);
            string sql = "select * from EcommerceGallery  with (NOLOCK) where IsActive=1 order by DisplayOrder,Name";

            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, sql))
                {
                    tmpS.Append("<table border=\"0\" cellpadding=\"4\" cellspacing=\"0\">\n");
                    tmpS.Append("<tr>\n");
                    while (rs.Read())
                    {
                        tmpS.Append("<td valign=\"bottom\" align=\"center\">");
                        string GalIcon = AppLogic.LookupImage("Gallery", DB.RSField(rs, "GalleryID"), "", SkinID, LocaleSetting);
                        tmpS.Append("<a target=\"_blank\" href=\"showgallery.aspx?galleryid=" + DB.RSFieldInt(rs, "GalleryID").ToString() + "\"><img border=\"0\" src=\"" + GalIcon + "?" + CommonLogic.GetRandomNumber(1, 1000000).ToString() + "\" /></a><br />\n");
                        tmpS.Append("<a target=\"_blank\" href=\"showgallery.aspx?galleryid=" + DB.RSFieldInt(rs, "GalleryID").ToString() + "\">" + DB.RSFieldByLocale(rs, "Name", LocaleSetting) + "</a>");
                        tmpS.Append("</td>\n");
                    }
                    tmpS.Append("</tr>\n");
                    tmpS.Append("</table>\n");
                }
            }

            if (CachingOn)
            {
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, tmpS.ToString(), AppLogic.CacheDurationMinutes());
            }
            return tmpS.ToString();
        }

        public static string GetGalleryName(string GalleryID, string LocaleSetting)
        {
            string tmpS = string.Empty;


            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, "Select GalleryName from EcommerceGallery  with (NOLOCK) where GalleryID=" + GalleryID.ToString()))
                {
                    if (rs.Read())
                    {
                        tmpS = DB.RSFieldByLocale(rs, "GalleryName", LocaleSetting);
                    }
                }
            }

            return tmpS;
        }

        public static string GetGalleryDir(string GalleryID)
        {
            string tmpS = string.Empty;

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, "Select DirectoryName from EcommerceGallery  with (NOLOCK) where GalleryID=" + GalleryID.ToString()))
                {
                    if (rs.Read())
                    {
                        tmpS = DB.RSField(rs, "DirectoryName");
                    }
                }
            }

            return tmpS;
        }

        public static string MakeProperPhoneFormat(string PhoneNumber)
        {
            return PhoneNumber;
        }

        public static bool ProductHasBeenDeleted(int ProductID)
        {
            return (DB.GetSqlN("Select count(A.Counter) as N from InventoryItem A with (NOLOCK) INNER JOIN InventoryItemWebOption B with (NOLOCK) " +
                "ON A.ItemCode = B.ItemCode where A.Status='A' and B.Published=1 and A.Counter=" + ProductID + " AND WebSiteCode =" + DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode)) == 0);
        }

        public static string GetAdminDir()
        {
            string AdminDir = AppLogic.AdminDir();
            if (AdminDir.Length == 0)
            {
                AdminDir = "admin";
            }
            if (AdminDir.EndsWith("/"))
            {
                AdminDir = AdminDir.Substring(0, AdminDir.Length - 1);
            }
            return AdminDir;
        }

        public static string GetAdminHTTPLocation(bool TryToUseSSL)
        {
            return GetStoreHTTPLocation(TryToUseSSL) + AppLogic.GetAdminDir() + "/";
        }

        public static bool OnLiveServer()
        {
            return CommonLogic.ServerVariables("HTTP_HOST").IndexOf(AppLogic.LiveServer(), StringComparison.InvariantCultureIgnoreCase) != -1;
        }

        public static int GetProductDisplayOrder(string ProductID, string CategoryID)
        {
            int tmp = 0;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "select DisplayOrder from ProductCategory with (NOLOCK) where ProductID=" + ProductID.ToString() + " and categoryid=" + CategoryID.ToString()))
                {
                    if (rs.Read())
                    {
                        tmp = DB.RSFieldInt(rs, "DisplayOrder");
                    }
                }
            }

            return tmp;
        }

        // returns the "next" product in this category, after the specified product
        // "next" is defined as either the product that is next higher display order, or same display order and next highest alphabetical order
        // is circular also (i.e. if last, return first)
        public static string GetNextProduct(string ProductID, string CategoryID, string DepartmentID, string ManufacturerID, int ProductTypeID, bool SortByLooks, bool includeKits, bool includePacks)
        {
            string sql = string.Empty;
            if (CategoryID.Length == 0 && DepartmentID.Length == 0 && ManufacturerID.Length == 0)
            {
                CategoryID = AppLogic.GetFirstProductEntityID(AppLogic.LookupHelper("Category"), ProductID, false);
            }
            string tbl = string.Empty;
            if (CategoryID.Length != 0)
            {
                tbl = "PC";

                sql = "SELECT A.Counter AS ProductID FROM InventoryItem A with (NOLOCK) " +
                    " INNER JOIN InventoryCategory B with (NOLOCK) ON A.ItemCode = B.ItemCode " +
                    " INNER JOIN InventoryItemWebOption C with (NOLOCK) ON A.ItemCode = C.ItemCode " +
                    " WHERE C.Published = 1 AND A.Status='A' AND C.WebSiteCode=" + DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode) +
                    " AND B.Counter=" + CategoryID.ToString();

            }
            else if (DepartmentID.Length != 0)
            {
                tbl = "PS";
                sql = "SELECT P.ProductID from (([Section] S with (NOLOCK) INNER JOIN ProductSection PS  with (NOLOCK) ON S.SectionID = PS.SectionID) INNER JOIN Product P  with (NOLOCK) ON PS.ProductID = P.ProductID) WHERE " + tbl + ".Sectionid=" + DepartmentID.ToString() + " and (P.Published = 1) AND (P.Deleted = 0) " + CommonLogic.IIF(includeKits, "", " and P.IsAKit=0") + CommonLogic.IIF(includePacks, "", " and P.IsAPack=0") + " and PS.Sectionid=" + DepartmentID.ToString();
            }
            else if (ManufacturerID.Length != 0)
            {
                tbl = "PM";
                sql = "SELECT P.ProductID from (([Manufacturer] M with (NOLOCK) INNER JOIN ProductManufacturer PM  with (NOLOCK) ON M.ManufacturerID = PM.ManufacturerID) INNER JOIN Product P  with (NOLOCK) ON PM.ProductID = P.ProductID) WHERE " + tbl + ".Manufacturerid=" + ManufacturerID.ToString() + " and (P.Published = 1) AND (P.Deleted = 0) " + CommonLogic.IIF(includeKits, "", " and P.IsAKit=0") + CommonLogic.IIF(includePacks, "", " and P.IsAPack=0") + " and PM.Manufacturerid=" + ManufacturerID.ToString();
            }
            if (ProductTypeID != 0)
            {
                sql += " and p.ProductTypeID=" + ProductTypeID.ToString();
            }
            var ds = DB.GetDS(sql, AppLogic.CachingOn, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()));
            if (ds.Tables[0].Rows.Count == 0)
            {
                ds.Dispose();
                return string.Empty;
            }
            int i = 0;
            bool found = false;
            for (i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                if (ds.Tables[0].Rows[i]["ProductID"].ToString() == ProductID.ToString())
                {
                    found = true;
                    break;
                }
            }
            string id = string.Empty;
            if (found)
            {
                if (i == ds.Tables[0].Rows.Count - 1)
                {
                    // if last, go to first
                    id = ds.Tables[0].Rows[0]["ProductID"].ToString();
                }
                else
                {
                    id = ds.Tables[0].Rows[i + 1]["ProductID"].ToString();
                }
            }
            ds.Dispose();
            return id;
        }

        // returns the "next" variant in this product, after the specified variant
        // "next" is defined as either the product that is next higher display order, or same display order and next highest alphabetical order
        // is circular also (i.e. if last, return first)
        public static string GetNextVariant(string ProductID, string VariantID)
        {
            string sql = "SELECT VariantID from ProductVariant with (NOLOCK) where ProductID=" + ProductID.ToString() + " and Deleted=0 order by DisplayOrder,Name";
            var ds = DB.GetDS(sql, false);
            if (ds.Tables[0].Rows.Count == 0)
            {
                ds.Dispose();
                return string.Empty;
            }
            int i = 0;
            bool found = false;
            for (i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                if (ds.Tables[0].Rows[i]["VariantID"].ToString() == VariantID.ToString())
                {
                    found = true;
                    break;
                }
            }
            string id = string.Empty;
            if (found)
            {
                if (i == ds.Tables[0].Rows.Count - 1)
                {
                    // if last, go to first
                    id = ds.Tables[0].Rows[0]["VariantID"].ToString();
                }
                else
                {
                    id = ds.Tables[0].Rows[i + 1]["VariantID"].ToString();
                }
            }
            ds.Dispose();
            return id;
        }

        public static string GetProductSequence(string direction, string ProductID, string EntityID, string EntityName, int ProductTypeID, bool SortByLooks, bool includeKits, bool includePacks, out string SEName)
        {
            if (false == "first".Equals(direction, StringComparison.InvariantCultureIgnoreCase) &&
                false == "last".Equals(direction, StringComparison.InvariantCultureIgnoreCase) &&
                false == "next".Equals(direction, StringComparison.InvariantCultureIgnoreCase) &&
                false == "previous".Equals(direction, StringComparison.InvariantCultureIgnoreCase))
            {
                direction = "first";
            }
            if (EntityName.Trim() == "")
            {
                EntityID = AppLogic.GetFirstProductEntityID(AppLogic.LookupHelper("Category"), ProductID, false);
                EntityName = "CATEGORY";
            }
            string sql = "eCommerceProductSequence " + DB.SQuote(direction) + ", " + ProductID.ToString() + "," + DB.SQuote(EntityName) + "," + EntityID.ToString() +
                         "," + ProductTypeID.ToString() + "," + CommonLogic.IIF(includeKits, 1, 0) + "," + CommonLogic.IIF(includePacks, 1, 0) + "," + CommonLogic.IIF(SortByLooks, 1, 0) + ","
                         + DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode) + ", " + DB.SQuote(((InterpriseSuiteEcommercePrincipal)HttpContext.Current.User).ThisCustomer.LanguageCode) + ", " + DB.SQuote(AppLogic.IsCBNMode().ToString());


            string id = Convert.ToString("0");

            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var dr = DB.GetRSFormat(con, sql))
                {
                    if (dr.Read())
                    {
                        id = dr["ProductID"].ToString();
                        SEName = CommonLogic.Left(Security.UrlEncode(SE.MungeName(dr["SEName"].ToString())), 90);
                    }
                    else
                    {
                        SEName = null;
                    }
                }
            }

            return id;
        }

        public static string GetPreviousVariant(string ProductID, string VariantID)
        {
            string sql = "SELECT VariantID from ProductVariant with (NOLOCK) where ProductID=" + ProductID.ToString() + " and deleted=0 order by DisplayOrder,Name";
            var ds = DB.GetDS(sql, false);
            if (ds.Tables[0].Rows.Count == 0)
            {
                ds.Dispose();
                return string.Empty;
            }
            int i = 0;
            for (i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                if (ds.Tables[0].Rows[i]["VariantID"].ToString() == VariantID.ToString())
                {
                    break;
                }
            }
            string id = string.Empty;
            if (i == 0)
            {
                // if first, go to last
                id = ds.Tables[0].Rows[ds.Tables[0].Rows.Count - 1]["VariantID"].ToString();
            }
            else
            {
                id = ds.Tables[0].Rows[i - 1]["VariantID"].ToString();
            }
            ds.Dispose();
            return id;
        }

        public static bool ManufacturerHasVisibleProducts(string ManufacturerID)
        {
            bool tmp = false;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "select count(*) as N from product with (NOLOCK) where ManufacturerID=" + ManufacturerID.ToString() + " and deleted=0 and published=1"))
                {
                    if (rs.Read())
                    {
                        tmp = (DB.RSFieldInt(rs, "N") != 0);
                    }
                }
            }
            return tmp;
        }

        public static bool ProductTypeHasVisibleProducts(string ProductTypeID)
        {
            return DB.GetSqlN("select count(*) as N from Product with (NOLOCK) where ProductTypeID=" + ProductTypeID.ToString() + " and Deleted=0 and Published=1") > 0;
        }

        public static string GetUserBox(Customer ThisCustomer, int SkinID)
        {
            var tmpS = new StringBuilder(4096);
            tmpS.Append("<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" >\n");
            tmpS.Append("<tr><td colspan=\"3\" height=20></td></tr>\n");
            tmpS.Append("<tr>\n");
            tmpS.Append("	<td colspan=\"2\" align=\"right\"><span style=\"color: white; font-size: 11px; font-weight: bold;\">" + GetString("common.cs.12", SkinID, ThisCustomer.LocaleSetting) + " <a class=\"DarkCellText\" href=\"account.aspx\"><b>" + ThisCustomer.FullName + "</b></a></span></td>\n");
            tmpS.Append("	<td width=\"25\"><img src=\"images/spacer.gif\" width=25\" height=\"1\" /></td>\n");
            tmpS.Append("</tr>\n");
            tmpS.Append("<tr><td colspan=\"3\" height=4></td></tr>\n");
            tmpS.Append("<tr>\n");
            tmpS.Append("	<td colspan=\"2\" align=\"right\"><span style=\"color: white; font-size: 11px; font-weight: bold;\"><a class=\"DarkCellText\" href=\"signout.aspx\"><b>" + GetString("common.cs.13", SkinID, ThisCustomer.LocaleSetting) + "</b></a></span></td>\n");
            tmpS.Append("	<td width=\"25\"><img src=\"images/spacer.gif\" width=25\" height=\"1\" /></td>\n");
            tmpS.Append("</tr>\n");
            tmpS.Append("<tr>\n");
            tmpS.Append("	<td colspan=\"3\"><img src=\"skins/Skin_(!SKINID!)/images/spacer.gif\" height=\"2\" width=\"1\" /></td></tr>\n");
            tmpS.Append("<tr>\n");
            tmpS.Append("	<td colspan=\"2\" align=\"right\"><span style=\"color: white; font-size: 11px; font-weight: bold;\"><a class=\"DarkCellText\" href=\"signin.aspx\"><b>" + GetString("common.cs.14", SkinID, ThisCustomer.LocaleSetting) + "</b></a></span></td>\n");
            tmpS.Append("	<td width=\"25\"><img src=\"images/spacer.gif\" width=25\" height=\"1\" /></td>\n");
            tmpS.Append("</tr>\n");
            tmpS.Append("</table>\n");
            return tmpS.ToString();
        }

        public static string GetPollBox(Customer thisCustomer, string PollID, bool large)
        {
            var tmpS = new StringBuilder(10000);
            tmpS.Append("<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border=\"0\" style=\"border-style: solid; border-width: 0px; border-color: #" + AppLogic.AppConfig("HeaderBGColor") + "\">\n");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
            tmpS.Append("<img src=\"" + AppLogic.LocateImageURL("skins/Skin_" + thisCustomer.SkinID.ToString() + "/images/" + CommonLogic.IIF(large, "poll.gif", "todayspoll.gif")) + "\" border=\"0\" /><br />");
            tmpS.Append("<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" style=\"" + AppLogic.AppConfig("BoxFrameStyle") + "\">\n");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");

            Poll showingPoll = null;
            if (CommonLogic.IsStringNullOrEmpty(PollID))
            {
                showingPoll = Poll.GetAnyPollNotVotedByThisCustomerYet(thisCustomer);
            }
            else
            {
                showingPoll = Poll.GetPoll(PollID, thisCustomer);
            }

            if (null != showingPoll)
            {
                tmpS.Append(
                    showingPoll.Display(thisCustomer, !large)
                );
            }

            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");
            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");
            return CommonLogic.IIF(null != showingPoll, tmpS.ToString(), string.Empty);
        }

        public static string GetHelpBox(int SkinID, bool includeFrame, string LocaleSetting, Parser UseParser)
        {
            //return Immediately once caching is off to reduce nesting
            if (!AppLogic.CachingOn)
            {
                return GenerateHelpBox(SkinID, includeFrame, LocaleSetting, UseParser);
            }

            string CacheName = string.Format("GetHelpBox_{0}_{1}_{2}", SkinID.ToString(), includeFrame.ToString(), LocaleSetting);
            string menu = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);

            if (menu.IsNullOrEmptyTrimmed())
            {
                menu = GenerateHelpBox(SkinID, includeFrame, LocaleSetting, UseParser);
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, menu, AppLogic.CacheDurationMinutes());
            }

            return menu;
        }

        public static string GetHelperBoxWithFrame(string content, int SkinID)
        {
            var tmpS = new StringBuilder(10000);
            tmpS.Append("<table cellpadding=\"2\" cellspacing=\"0\" border=\"0\" style=\"border-style: solid; border-width: 0px; border-color: #" + AppLogic.AppConfig("HeaderBGColor") + "\">\n");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
            tmpS.Append("<img src=\"" + AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/help.gif") + "\" border=\"0\" /><br />");
            tmpS.Append("<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" style=\"" + AppLogic.AppConfig("BoxFrameStyle") + "\">\n");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");

            tmpS.Append(content);

            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");
            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");

            return tmpS.ToString();
        }

        private static string GenerateHelpBox(int SkinID, bool includeFrame, string LocaleSetting, Parser UseParser)
        {
            var tmpS = new StringBuilder(10000);
            if (includeFrame)
            {
                tmpS.Append("<table cellpadding=\"2\" cellspacing=\"0\" border=\"0\" style=\"border-style: solid; border-width: 0px; border-color: #" + AppLogic.AppConfig("HeaderBGColor") + "\">\n");
                tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
                tmpS.Append("<img src=\"" + AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/help.gif") + "\" border=\"0\" /><br />");
                tmpS.Append("<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" style=\"" + AppLogic.AppConfig("BoxFrameStyle") + "\">\n");
                tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
            }

            var t1 = new Topic("helpbox", LocaleSetting, SkinID, UseParser);
            tmpS.Append(t1.Contents);

            if (includeFrame)
            {
                tmpS.Append("</td></tr>\n");
                tmpS.Append("</table>\n");
                tmpS.Append("</td></tr>\n");
                tmpS.Append("</table>\n");
            }
            return tmpS.ToString();
        }

        public static string GetSocialMediaSubscribeBox(int skinID, string localeSetting, Parser userParser)
        {
            if (!AppLogic.CachingOn)
            {
                return GenerateSocialMediaSubscribeBox(skinID, localeSetting, userParser);
            }

            string CacheName = string.Format("GetSocialMediaSubscribeBox_{0}_{1}", skinID.ToString(), localeSetting);
            string menu = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);

            if (string.IsNullOrEmpty(menu))
            {
                menu = GenerateSocialMediaSubscribeBox(skinID, localeSetting, userParser);
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, menu, AppLogic.CacheDurationMinutes());
            }

            return menu;
        }

        public static string GenerateSocialMediaSubscribeBox(int SkinID, string LocaleSetting, Parser UserParser)
        {
            StringBuilder tmpS = new StringBuilder();

            if (!AppLogic.AppConfigBool("ShowSocialMediaSubscribeBox"))
            {
                return string.Empty;
            }

            var t1 = new Topic("socialmediasubscribebox", LocaleSetting, SkinID, UserParser);
            tmpS.Append(t1.Contents);

            return tmpS.ToString();
        }

        public static string GetSocialMediaFeedBox(int skinID, string localeSetting, Parser userParser)
        {
            if (!AppLogic.CachingOn)
            {
                return GenerateSocialMediaFeedBox(skinID, localeSetting, userParser);
            }

            string CacheName = string.Format("GetSocialMediaFeedBox_{0}_{1}", skinID.ToString(), localeSetting);
            string menu = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);

            if (string.IsNullOrEmpty(menu))
            {
                menu = GenerateSocialMediaFeedBox(skinID, localeSetting, userParser);
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, menu, AppLogic.CacheDurationMinutes());
            }

            return menu;
        }

        public static string GenerateSocialMediaFeedBox(int SkinID, string LocaleSetting, Parser UserParser)
        {
            StringBuilder tmpS = new StringBuilder();

            if (!AppLogic.AppConfigBool("ShowSocialMediaFeedBox"))
            {
                return string.Empty;    
            }

            string sFeedAPILink = AppLogic.AppConfig("SocialMediaFeedBoxAPI");

            if (sFeedAPILink != string.Empty)
            {
                tmpS.Append("<script src=\"jscripts/jquery/jquery.bxSlider.js\" type=\"text/javascript\"></script>");
                tmpS.Append(" <script type=\"text/javascript\">");
                tmpS.Append(" function fbFetch() {");
                tmpS.Append(string.Format(" var url=\"{0}&callback=?\";", sFeedAPILink));
                tmpS.Append(" $.getJSON(url, function (json) {");
                tmpS.Append(" if (json.data == null) {");
                tmpS.Append(" $('#fb_feed').attr(\"style\", \"display:none;\");");
                tmpS.Append(" console.log(json);");
                tmpS.Append(" return;");
                tmpS.Append(" }");
                tmpS.Append(string.Format(" var html = \"<b>{0}</b><br><ul id='slider1' style='list-style: none outside none;padding:0px !important;'>\";", GetString("socialmedia.aspx.1",SkinID, LocaleSetting)));
                tmpS.Append(" $.each(json.data, function (i, fb) {");
                tmpS.Append(" html += \"<li><a class='feedbox_nav' target='_blank' href='http://www.facebook.com&#47;\" + fb.from.id + \"&#47;?sk=wall'>\" + $('<div>').html(fb.message.substring(0, 110) + '...').text() + \"</a></li>\";");
                tmpS.Append(" });");
                tmpS.Append(" html += \"</ul>\";");
                tmpS.Append(" $('.socialmedia_feedbox').html(html);");
                tmpS.Append(" $(\"#slider1\").bxSlider({ prevText: '', nextText: '', infiniteLoop: false, auto: true });");
                tmpS.Append(" });");
                tmpS.Append(" };");
                tmpS.Append(" jQuery(document).ready(function ($) {");
                tmpS.Append(" fbFetch();");
                tmpS.Append(" });");
                tmpS.Append(" 	</script>");
                tmpS.Append(" <div class=\"socialmedia_feedbox\" id=\"fb_feed\">");
                tmpS.Append(" <p align=center><br><br>Loading<br>Facebook Wall Feeds...</p>");
                tmpS.Append(" 		</div>");
            }
            return tmpS.ToString();
        }

        public static string GetTechTalkBox(int SkinID)
        {
            //return Immediately once caching is off to reduce nesting
            if (!AppLogic.CachingOn)
            {
                return GenerateTechTalkBox(SkinID);
            }

            string CacheName = "GetTechTalkBox_" + SkinID.ToString();
            var requestCachingEngine = new InterpriseSuiteEcommerceCommon.Tool.ApplicationCachingEngine();
            string box = requestCachingEngine.GetItem(CacheName) as string;

            if (string.IsNullOrEmpty(box))
            {
                box = GenerateTechTalkBox(SkinID);
                requestCachingEngine.AddItem(CacheName, box, AppLogic.CacheDurationMinutes());
            }
            return box;
        }

        public static string GenerateTechTalkBox(int skinId)
        {
            var tmpS = new StringBuilder(10000);
            tmpS.Append("<table cellpadding=\"2\" cellspacing=\"0\" border=\"0\" style=\"border-style: solid; border-width: 0px; border-color: #" + AppLogic.AppConfig("HeaderBGColor") + "\">\n");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
            tmpS.Append("<a href=\"techtalk.aspx\"><img src=\"" + AppLogic.LocateImageURL("skins/Skin_" + skinId.ToString() + "/images/learn.gif") + "\" border=\"0\" /></a><br />");
            tmpS.Append("<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" style=\"" + AppLogic.AppConfig("BoxFrameStyle") + "\">\n");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");

            tmpS.Append("NOT IMPLEMENTED YET");

            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");
            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");
            return tmpS.ToString();
        }

        public static string GetTechTalkBoxExpanded(int SkinID)
        {
            //return Immediately once caching is off to reduce nesting
            if (!AppLogic.CachingOn)
            {
                return GenerateTalkBoxExpanded(SkinID);
            }

            string CacheName = "GetTechTalkBoxExpanded_" + SkinID.ToString();
            var requestCachingEngine = new InterpriseSuiteEcommerceCommon.Tool.ApplicationCachingEngine();
            string box = requestCachingEngine.GetItem(CacheName) as string;
            if (string.IsNullOrEmpty(box))
            {
                box = GenerateTalkBoxExpanded(SkinID);
                requestCachingEngine.AddItem(CacheName, box, AppLogic.CacheDurationMinutes());
            }
            return box;
        }

        public static string GenerateTalkBoxExpanded(int SkinID)
        {
            var tmpS = new StringBuilder(10000);
            tmpS.Append("<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border=\"0\" style=\"border-style: solid; border-width: 0px; border-color: #" + AppLogic.AppConfig("HeaderBGColor") + "\">\n");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
            tmpS.Append("<a href=\"techtalk.aspx\"><img src=\"" + AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/learnexpanded.gif") + "\" border=\"0\" /></a><br />");
            tmpS.Append("<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" style=\"" + AppLogic.AppConfig("BoxFrameStyle") + "\">\n");
            tmpS.Append("<tr><td width=\"100%\" align=\"left\" valign=\"top\">\n");

            tmpS.Append("NOT IMPLEMENTED YET");

            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");
            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");
            return tmpS.ToString();
        }

        public static string GetManufacturersBoxExpanded(int SkinID, string LocaleSetting)
        {
            string CacheName = "GetManufacturersBoxExpanded_" + SkinID.ToString() + "_" + LocaleSetting;
            if (AppLogic.CachingOn)
            {
                return CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
            }

            var tmpS = new StringBuilder(10000);
            tmpS.Append("<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border=\"0\" style=\"border-style: solid; border-width: 0px; border-color: #" + AppLogic.AppConfig("HeaderBGColor") + "\">\n");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
            tmpS.Append("<a href=\"manufacturers.aspx\"><img src=\"" + AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/manufacturersbox.gif") + "\" border=\"0\" /></a><br />");
            tmpS.Append("<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" style=\"" + AppLogic.AppConfig("BoxFrameStyle") + "\">\n");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");

            tmpS.Append("<p><b>" + GetString("common.cs.15", SkinID, LocaleSetting) + "</b></p>\n");
            var ds = DB.GetDS("select * from manufacturer  with (NOLOCK) where deleted=0 order by DisplayOrder,Name", AppLogic.CachingOn, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()));

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                tmpS.Append("<b class=\"a4\"><a href=\"" + SE.MakeManufacturerLink(DB.RowField(row, "ManufacturerID"), DB.RowField(row, "SEName")) + "\"><font style=\"font-size: 14px;\">" + DB.RowFieldByLocale(row, "Name", LocaleSetting));
                if (DB.RowFieldByLocale(row, "Summary", LocaleSetting).Length != 0)
                {
                    tmpS.Append(": " + DB.RowFieldByLocale(row, "Summary", LocaleSetting));
                }
                tmpS.Append("</font></a></b><br />\n");
                if (DB.RowFieldByLocale(row, "Description", LocaleSetting).Length != 0)
                {
                    string tmpD = DB.RowFieldByLocale(row, "Description", LocaleSetting);
                    if (AppLogic.ReplaceImageURLFromAssetMgr)
                    {
                        tmpD = tmpD.Replace("../images", "images");
                    }
                    tmpS.Append("<span class=\"a2\">" + tmpD + "</span><br />\n");
                }
                tmpS.Append("<div class=\"a1\" style=\"PADDING-BOTTOM: 10px\">\n");
                if (DB.RowField(row, "URL").Length != 0)
                {
                    tmpS.Append("<a href=\"" + DB.RowField(row, "URL") + "\" target=\"_blank\">" + DB.RowField(row, "URL") + "</a>");
                }
                tmpS.Append("</div><br />\n");
            }
            ds.Dispose();

            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");
            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");
            if (CachingOn)
            {
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, tmpS.ToString(), AppLogic.CacheDurationMinutes());
            }
            return tmpS.ToString();
        }

        public static string GetSpecialsBoxExpanded(string CategoryID, int showNum, bool useCache, bool showPics, bool IncludeFrame, string teaser, int SkinID, string LocaleSetting, Customer ViewingCustomer)
        {
            string CacheName = "GetSpecialsBoxExpanded_" + CategoryID.ToString() + "_" + showNum.ToString() + "_" + showPics.ToString() + "_" + teaser + "_" + SkinID.ToString() + "_" + LocaleSetting + "_" + ViewingCustomer.CurrencyCode;
            string ImgFilename = string.Empty;
            string ImgUrl = string.Empty;
            bool existing = false;
            bool exists = false;

            if (AppLogic.CachingOn && useCache)
            {
                string htmlTest = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
                if (!htmlTest.IsNullOrEmptyTrimmed()) return htmlTest;
            }

            var tmpS = new StringBuilder(10000);
            bool showItemPrice = AppLogic.AppConfigBool("FeaturedItemsDisplayPrice");

            if (IncludeFrame)
            {
                tmpS.Append("<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border=\"0\" style=\"border-style: solid; border-width: 0px; border-color: #" + AppLogic.AppConfig("HeaderBGColor") + "\">\n");
                tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
                tmpS.Append("<a href=\"featureditems.aspx?resetfilter=true\"><img src=\"" + AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/Specialsexpanded.gif") + "\" border=\"0\" /></a><br />");
                tmpS.Append("<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" style=\"" + AppLogic.AppConfig("BoxFrameStyle") + "\">\n");
                tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
            }

            tmpS.Append("<p><b>" + teaser + "</b></p>\n");

            string query = string.Format("exec EcommerceFeaturedProduct @LocaleSetting = {0}, @WebSiteCode = {1},  @CurrentDate = {2}, @ContactCode = {3}",
                    DB.SQuote(LocaleSetting),
                    DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                    DB.SQuote(Localization.DateTimeStringForDB(DateTime.Now)),
                    DB.SQuote(ViewingCustomer.ContactCode));

            DataSet ds = DB.GetDS(query, false);

            var lstItemCodes = ds.Tables[0].Rows.OfType<DataRow>()
                                                .Select(r => DB.SQuote(DB.RowField(r, "ItemCode")))
                                                .AsParallel()
                                                .ToArray();
            var lstOverrideImages = InterpriseHelper.GetInventoryOverideImageList(string.Join(",", lstItemCodes));
            var attList = GetSEImageAttributeByItemCodes(lstItemCodes, "ICON", AppLogic.GetLanguageCode(ViewingCustomer.LocaleSetting));

            //for Featured Item layout type
            if (true == AppLogic.AppConfig("FeaturedItemLayout").Equals("List", StringComparison.InvariantCultureIgnoreCase))
            {
                tmpS.Append("<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border=\"0\">\n");
                int i = 1;
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string displayName = CommonLogic.IIF(string.IsNullOrEmpty(DB.RowField(row, "ItemDescription")),
                                                                DB.RowField(row, "ItemName"),
                                                                DB.RowField(row, "ItemDescription"));
                    int counter = DB.RowFieldInt(row, "Counter");
                    string itemCode = DB.RowField(row, "ItemCode");

                    if (i > showNum)
                    {
                        tmpS.Append("<tr><td " + CommonLogic.IIF(showPics, "colspan=\"2\"", "") +
                        "><hr size=\"1\" class=\"LightCellText\"/><a href=\"featureditems.aspx?resetfilter=true\">" +
                        GetString("common.cs.17", SkinID, LocaleSetting) + "</a></td></tr>");
                        break;
                    }
                    if (i > 1)
                    {
                        tmpS.Append("<tr><td " + CommonLogic.IIF(showPics, "colspan=\"2\"", "") + "><hr size=\"1\" class=\"LightCellText\"/></td></tr>");
                    }
                    tmpS.Append("<tr>");

                    ImgFilename = lstOverrideImages.FirstOrDefault(m => m.Key == itemCode).Value;
                    ImgFilename = CommonLogic.IIF(!string.IsNullOrEmpty(ImgFilename), ImgFilename, string.Empty);
                    existing = !string.IsNullOrEmpty(ImgFilename);

                    ImgUrl = LocateImageFilenameUrl("Product", itemCode, "icon", ImgFilename, AppLogic.AppConfigBool("Watermark.Enabled"), out exists);
                    if (showPics)
                    {
                        var att = attList.FirstOrDefault(l => l.ItemCode == itemCode);

                        string title = string.Empty;
                        string alt = string.Empty;
                        if (att != null)
                        {
                            title = att.Title;
                            alt = att.Alt;
                        }

                        tmpS.Append("<td align=\"left\" valign=\"top\">\n");
                        tmpS.Append("<a href=\"" + SE.MakeProductLink(counter.ToString(), displayName) + "\">");
                        tmpS.Append("<img align=\"center\" src=\"" + ImgUrl + "\" border=\"0\" title=\"" + title + "\" alt=\"" + alt + "\" />");
                        tmpS.Append("</a>");
                        tmpS.Append("</td>");
                    }

                    tmpS.Append("<td align=\"left\" valign=\"top\">\n");
                    tmpS.Append("<b class=\"a4\">");
                    tmpS.Append("<a href=\"" + SE.MakeProductLink(counter.ToString(), displayName) + "\">" + Security.HtmlEncode(displayName));
                    tmpS.Append("</a>");

                    if (DB.RowFieldByLocale(row, "Summary", LocaleSetting).Length != 0)
                    {
                        tmpS.Append("<br />" + DB.RowFieldByLocale(row, "Summary", LocaleSetting));
                    }
                    tmpS.Append("</b><br />\n");

                    if (showItemPrice)
                    {
                        decimal promotionalPrice = 0;
                        decimal price = Math.Round(InterpriseHelper.GetSalesPriceAndTax(Customer.Current.CustomerCode, itemCode, Customer.Current.CurrencyCode, 1, "EACH", AppLogic.AppConfigBool("VAT.Enabled"), ref promotionalPrice), 2);

                        if (promotionalPrice > 0)
                        {
                            tmpS.Append("<i><strike>" + AppLogic.GetString("showproduct.aspx.33", Customer.Current.SkinID, Customer.Current.LocaleSetting) + " " + InterpriseHelper.FormatCurrencyForCustomer(price, Customer.Current.CurrencyCode) + "</i></strike>");
                            tmpS.Append("<b><br/>" + AppLogic.GetString("showproduct.aspx.34", Customer.Current.SkinID, Customer.Current.LocaleSetting) + " " + InterpriseHelper.FormatCurrencyForCustomer(Math.Round(promotionalPrice, 2), Customer.Current.CurrencyCode) + "</b>");
                        }
                        else
                        {
                            if (DB.RowField(row, "ItemType") == "Kit")
                            {
                                decimal kitPrice = Math.Round(InterpriseHelper.InventoryKitPackagePrice(itemCode, Customer.Current.CurrencyCode).TryParseDecimal().Value, 2);
                                tmpS.Append(AppLogic.GetString("showproduct.aspx.33", Customer.Current.SkinID, Customer.Current.LocaleSetting) + " " + InterpriseHelper.FormatCurrencyForCustomer(kitPrice, Customer.Current.CurrencyCode));
                            }
                            else
                            {
                                tmpS.Append(AppLogic.GetString("showproduct.aspx.33", Customer.Current.SkinID, Customer.Current.LocaleSetting) + " " + InterpriseHelper.FormatCurrencyForCustomer(price, Customer.Current.CurrencyCode));
                            }
                        }
                    }

                    tmpS.Append("<div class=\"a1\" style=\"PADDING-BOTTOM: 10px\">\n");
                    tmpS.Append("<a href=\"" + SE.MakeProductLink(counter.ToString(), displayName) + "\">");
                    tmpS.Append(GetString("common.cs.16", SkinID, LocaleSetting));
                    tmpS.Append("</a>");
                    tmpS.Append("</div>\n");
                    tmpS.Append("</td>");
                    tmpS.Append("</tr>");
                    i++;
                }
                tmpS.Append("</table>\n");
                ds.Dispose();


                if (IncludeFrame)
                {
                    tmpS.Append("</td></tr>\n");
                    tmpS.Append("</table>\n");
                    tmpS.Append("</td></tr>\n");
                    tmpS.Append("</table>\n");
                }

                if (CachingOn && useCache)
                {
                    CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, tmpS.ToString(), AppLogic.CacheDurationMinutes());
                }
                return tmpS.ToString();
            }
            else
            {
                tmpS.Append("<table width=\"0%\" cellpadding=\"2\" cellspacing=\"2\" border=\"0\">\n");
                tmpS.Append("<tr>");
                int i = 1;

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    int counter = DB.RowFieldInt(row, "Counter");
                    string displayName = CommonLogic.IIF(string.IsNullOrEmpty(DB.RowField(row, "ItemDescription")),
                                                        DB.RowField(row, "ItemName"),
                                                        DB.RowField(row, "ItemDescription"));
                    string itemCode = DB.RowField(row, "ItemCode");

                    if (i > showNum)
                    {
                        tmpS.Append("</tr><tr><td " + CommonLogic.IIF(showPics, "colspan=\"" + AppLogic.AppConfig("FeaturedItemColumn") + "\"", "") +
                        "><hr size=\"1\" class=\"LightCellText\"/><a href=\"featureditems.aspx?resetfilter=true\">" +
                        GetString("common.cs.17", SkinID, LocaleSetting) + "</a></td></tr><tr>");
                        break;
                    }

                    ImgFilename = lstOverrideImages.FirstOrDefault(m => m.Key == itemCode).Value;
                    existing = !string.IsNullOrEmpty(ImgFilename);
                    ImgFilename = CommonLogic.IIF(!string.IsNullOrEmpty(ImgFilename), ImgFilename, string.Empty);
                    ImgUrl = LocateImageFilenameUrl("product", itemCode, "icon", ImgFilename, AppLogic.AppConfigBool("Watermark.Enabled"), out exists);

                    tmpS.Append("<td valign=\"top\" width=\"0%\" style=\"border: 1px solid rgb(204, 204, 204); background-color: rgb(252, 253, 253); table-layout: fixed;\"><table cellpadding=\"2\" cellspacing=\"0\">");
                    if (showPics)
                    {
                        var att = attList.FirstOrDefault(l => l.ItemCode == itemCode);

                        string title = string.Empty;
                        string alt = string.Empty;
                        if (att != null)
                        {
                            title = att.Title;
                            alt = att.Alt;
                        }

                        tmpS.Append("<tr>");
                        tmpS.Append("<td align=\"left\" valign=\"top\" style=\"white-space: pre-wrap; word-wrap: break-word;\">\n");
                        tmpS.Append("<a href=\"" + SE.MakeProductLink(counter.ToString(), displayName) + "\">");
                        tmpS.Append("<img align=\"center\" src=\"" + ImgUrl + "\" border=\"0\" title=\"" + title + "\" alt=\"" + alt + "\" />");
                        tmpS.Append("</a>");
                        tmpS.Append("</td>");
                        tmpS.Append("</tr>");
                    }

                    tmpS.Append("<tr>");
                    tmpS.Append("<td align=\"left\" valign=\"top\" style=\"white-space: pre-wrap; word-wrap: break-word;\">\n");
                    tmpS.Append("<b class=\"a4\">");
                    tmpS.Append("<a href=\"" + SE.MakeProductLink(counter.ToString(), displayName) + "\">" + Security.HtmlEncode(displayName));
                    tmpS.Append("</a>");

                    if (DB.RowFieldByLocale(row, "Summary", LocaleSetting).Length != 0)
                    {
                        tmpS.Append("<br />" + DB.RowFieldByLocale(row, "Summary", LocaleSetting));
                    }
                    tmpS.Append("</b><br />\n");

                    if (showItemPrice)
                    {
                        decimal promotionalPrice = 0;
                        decimal price = 0;

                        price = Math.Round(InterpriseHelper.GetSalesPriceAndTax(Customer.Current.CustomerCode, itemCode, Customer.Current.CurrencyCode, 1, "EACH", AppLogic.AppConfigBool("VAT.Enabled"), ref promotionalPrice), 2);
                        if (promotionalPrice > 0)
                        {
                            tmpS.Append("<i><strike>" + AppLogic.GetString("showproduct.aspx.33", Customer.Current.SkinID, Customer.Current.LocaleSetting) + " " + InterpriseHelper.FormatCurrencyForCustomer(price, Customer.Current.CurrencyCode) + "</i></strike>");
                            tmpS.Append("<b><br/>" + AppLogic.GetString("showproduct.aspx.34", Customer.Current.SkinID, Customer.Current.LocaleSetting) + " " + InterpriseHelper.FormatCurrencyForCustomer(Math.Round(promotionalPrice, 2), Customer.Current.CurrencyCode) + "</b>");
                        }
                        else if (DB.RowField(row, "ItemType") == "Kit")
                        {
                            decimal kitPrice = 0;
                            kitPrice = Math.Round(decimal.Parse(InterpriseHelper.InventoryKitPackagePrice(itemCode, Customer.Current.CurrencyCode)), 2);
                            tmpS.Append(AppLogic.GetString("showproduct.aspx.33", Customer.Current.SkinID, Customer.Current.LocaleSetting) + " " + InterpriseHelper.FormatCurrencyForCustomer(kitPrice, Customer.Current.CurrencyCode));
                        }
                        else
                        {
                            tmpS.Append(AppLogic.GetString("showproduct.aspx.33", Customer.Current.SkinID, Customer.Current.LocaleSetting) + " " + InterpriseHelper.FormatCurrencyForCustomer(price, Customer.Current.CurrencyCode));
                        }
                    }

                    tmpS.Append("<div class=\"a1\" style=\"PADDING-BOTTOM: 10px\">\n");
                    tmpS.Append("<a href=\"" + SE.MakeProductLink(counter.ToString(), displayName) + "\">");
                    tmpS.Append(GetString("common.cs.16", SkinID, LocaleSetting));
                    tmpS.Append("</a>");
                    tmpS.Append("</div>\n");
                    tmpS.Append("</td>");
                    tmpS.Append("</tr></table>");

                    if ((i % int.Parse(AppLogic.AppConfig("FeaturedItemsColumn"))) == 0 && i == showNum)
                    {
                        tmpS.Append("</tr><tr>");
                    }
                    else if ((i % int.Parse(AppLogic.AppConfig("FeaturedItemsColumn"))) == 0)
                    {
                        tmpS.Append("</tr><tr>");
                    }
                    i++;
                }

                tmpS.Append("</tr>");
                tmpS.Append("</table>\n");
                ds.Dispose();

                if (IncludeFrame)
                {
                    tmpS.Append("</td></tr>\n");
                    tmpS.Append("</table>\n");
                    tmpS.Append("</td></tr>\n");
                    tmpS.Append("</table>\n");
                }

                if (CachingOn && useCache)
                {
                    CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, tmpS.ToString(), AppLogic.CacheDurationMinutes());
                }
                return tmpS.ToString();
            }
        }

        public static string GetSpecialsBoxExpandedRandom(string CategoryID, bool showPics, bool IncludeFrame, string teaser, int SkinID, string LocaleSetting, Customer ViewingCustomer)
        {
            var tmpS = new StringBuilder(4096);
            if (IncludeFrame)
            {
                tmpS.Append("<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border=\"0\" style=\"border-style: solid; border-width: 0px; border-color: #" + AppLogic.AppConfig("HeaderBGColor") + "\">\n");
                tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
                tmpS.Append("<a href=\"featureditems.aspx?resetfilter=true\"><img src=\"" + AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/Specialsexpanded.gif") + "\" border=\"0\" /></a><br />");
                tmpS.Append("<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" style=\"" + AppLogic.AppConfig("BoxFrameStyle") + "\">\n");
                tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
            }

            tmpS.Append("<p><b>" + teaser + "</b></p>\n");

            string sql = string.Format("select counter, itemcode, itemname, itemdescription, webdescription, summary from EcommerceViewProduct with (NOLOCK) where published = 1 and isfeatured = 1 and CheckOutOption = 0 and shortstring = {0} AND WebSiteCode = {1} {2}", DB.SQuote(LocaleSetting), DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                         CommonLogic.IIF(!string.IsNullOrEmpty(Customer.Current.ProductFilterID), string.Format(" AND ItemCode IN (SELECT DISTINCT(ItemCode) FROM InventoryProductFilterTemplateItem WHERE TemplateID = '{0}')", Customer.Current.ProductFilterID), string.Empty));
            var ds = DB.GetDS(sql, false, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()));
            int NumRecs = ds.Tables[0].Rows.Count;
            int ShowRecNum = CommonLogic.GetRandomNumber(1, NumRecs);
            tmpS.Append("<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border=\"0\">\n");
            int i = 1;
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string displayName = DB.RowField(row, "ItemDescription");
                if (CommonLogic.IsStringNullOrEmpty(displayName))
                {
                    displayName = DB.RowField(row, "ItemName");
                }

                if (i == ShowRecNum)
                {
                    tmpS.Append("<tr>");
                    string ImgUrl = string.Empty;
                    string productLink = SE.MakeProductLink(DB.RowField(row, "Counter"), displayName);

                    bool m_WatermarksEnabled = AppLogic.AppConfigBool("Watermark.Enabled");
                    if (m_WatermarksEnabled)
                    {
                        ImgUrl = string.Format("watermark.axd?counter={0}&size=icon", DB.RowFieldInt(row, "Counter").ToString());
                    }
                    else
                    {
                        ImgUrl = AppLogic.LookupImage("Product", DB.RowField(row, "Counter"), "icon", SkinID, LocaleSetting);
                    }
                    if (showPics)
                    {
                        tmpS.Append("<td align=\"left\" valign=\"top\">\n");
                        tmpS.Append("<a href=\"" + productLink + "\">");
                        tmpS.Append("<img align=\"left\" src=\"" + ImgUrl + "\" border=\"0\" />");
                        tmpS.Append("</a>");
                        tmpS.Append("</td>");
                    }

                    tmpS.Append("<td align=\"left\" valign=\"top\">\n");
                    tmpS.Append("<b class=\"a4\">");
                    tmpS.Append("<a href=\"" + productLink + "\">" + DB.RowFieldByLocale(row, "ItemDescription", LocaleSetting));
                    tmpS.Append("</a>");

                    if (DB.RowFieldByLocale(row, "Summary", LocaleSetting).Length != 0)
                    {
                        tmpS.Append("<br />" + DB.RowFieldByLocale(row, "Summary", LocaleSetting));
                    }

                    tmpS.Append("</b><br />\n");
                    if (DB.RowFieldByLocale(row, "WebDescription", LocaleSetting).Length != 0)
                    {
                        string tmpD = DB.RowFieldByLocale(row, "WebDescription", LocaleSetting);
                        if (AppLogic.ReplaceImageURLFromAssetMgr)
                        {
                            tmpD = tmpD.Replace("../images", "images");
                        }
                        tmpS.Append("<span class=\"a2\">" + tmpD + "</span><br />\n");
                    }
                    else
                    {
                        string tmpD = DB.RowFieldByLocale(row, "ItemDescription", LocaleSetting);
                        if (AppLogic.ReplaceImageURLFromAssetMgr)
                        {
                            tmpD = tmpD.Replace("../images", "images");
                        }
                        tmpS.Append("<span class=\"a2\">" + tmpD + "</span><br />\n");
                    }

                    tmpS.Append("<div class=\"a1\" style=\"PADDING-BOTTOM: 10px\">\n");
                    tmpS.Append("<a href=\"" + productLink + "\">");
                    tmpS.Append(GetString("common.cs.16", SkinID, LocaleSetting));
                    tmpS.Append("</a>");
                    tmpS.Append("</div>\n");
                    tmpS.Append("</td>");
                    tmpS.Append("</tr>");
                }
                i++;
            }

            tmpS.Append("<tr><td " + CommonLogic.IIF(showPics, "colspan=\"2\"", "") + "><hr size=\"1\" class=\"LightCellText\"/><a href=\"featureditems.aspx?resetfilter=true\">Show me more specials...</a></td></tr>");
            tmpS.Append("</table>\n");
            ds.Dispose();

            if (IncludeFrame)
            {
                tmpS.Append("</td></tr>\n");
                tmpS.Append("</table>\n");
                tmpS.Append("</td></tr>\n");
                tmpS.Append("</table>\n");
            }

            return tmpS.ToString();
        }

        public static string GetSearchBox(int SkinID, string LocaleSetting)
        {
            //return immediately once caching is off to reduce nesting
            if (!AppLogic.CachingOn)
            {
                return GenerateSearchBox(SkinID, LocaleSetting);
            }

            string CacheName = "GetSearchBox_" + SkinID.ToString() + "_" + LocaleSetting;
            string box = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
            if (box.IsNullOrEmptyTrimmed())
            {
                box = GenerateSearchBox(SkinID, LocaleSetting);
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, box, AppLogic.CacheDurationMinutes());
            }
            return box;
        }

        public static string GenerateSearchBox(int SkinID, string LocaleSetting)
        {
            var tmpS = new StringBuilder(10000);
            tmpS.Append("<table cellpadding=\"2\" cellspacing=\"0\" border=\"0\" style=\"border-style: solid; border-width: 0px; border-color: #" + AppLogic.AppConfig("HeaderBGColor") + "\">\n");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");
            tmpS.Append("<img src=\"" + AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/search.gif", LocaleSetting) + "\" border=\"0\" /><br />");
            tmpS.Append("<table width=\"100%\" cellpadding=\"4\" cellspacing=\"0\" border=\"0\" style=\"" + AppLogic.AppConfig("BoxFrameStyle") + "\">\n");
            tmpS.Append("<tr><td align=\"left\" valign=\"top\">\n");

            tmpS.Append("<script type=\"text/javascript\" Language=\"JavaScript\">\n");
            tmpS.Append("function SearchBoxForm_Validator(theForm)\n");
            tmpS.Append("{\n");
            tmpS.Append("  $disableSubmit(theForm);\n");
            tmpS.Append("  if (theForm.SearchTerm.value.length < " + AppLogic.AppConfig("MinSearchStringLength") + ")\n");
            tmpS.Append("  {\n");
            tmpS.Append("    alert('" + string.Format(GetString("common.cs.19", SkinID, LocaleSetting), AppLogic.AppConfig("MinSearchStringLength")) + "');\n");
            tmpS.Append("    theForm.SearchTerm.focus();\n");
            tmpS.Append("    $enableSubmit(theForm);\n");
            tmpS.Append("    return (false);\n");
            tmpS.Append("  }\n");
            tmpS.Append("  return (true);\n");
            tmpS.Append("}\n");
            tmpS.Append("</script>\n");

            tmpS.Append("<form style=\"margin-top: 0px; margin-bottom: 0px;\" name=\"SearchBoxForm\" action=\"searchadv.aspx\" method=\"GET\" onsubmit=\"return SearchBoxForm_Validator(this)\">\n");
            tmpS.Append("<input type=\"hidden\" name=\"IsSubmit\" value=\"true\" />" + GetString("common.cs.23", SkinID, LocaleSetting) + " <input name=\"SearchTerm\" size=\"10\" /><img src=\"images/spacer.gif\" width=\"4\" height=\"4\" /><INPUT NAME=\"submit\" TYPE=\"Image\" ALIGN=\"absmiddle\" src=\"" + AppLogic.LocateImageURL("skins/Skin_" + SkinID.ToString() + "/images/go.gif") + "\" border=\"0\" />\n");
            tmpS.Append("</form>");
            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");
            tmpS.Append("</td></tr>\n");
            tmpS.Append("</table>\n");
            return tmpS.ToString();

        }

        public static string GetPollCategories(string PollID)
        {
            var tmpS = new StringBuilder(1000);
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "select * from Pollcategory  with (NOLOCK) where Pollid=" + PollID.ToString()))
                {
                    while (rs.Read())
                    {
                        if (tmpS.Length != 0)
                        {
                            tmpS.Append(",");
                        }
                        tmpS.Append(DB.RSField(rs, "CategoryID").ToString());
                    }
                }
            }

            return tmpS.ToString();
        }

        public static string GetPollSections(string PollID)
        {
            var tmpS = new StringBuilder(1000);
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "select * from Pollsection  with (NOLOCK) where Pollid=" + PollID.ToString()))
                {
                    while (rs.Read())
                    {
                        if (tmpS.Length != 0)
                        {
                            tmpS.Append(",");
                        }
                        tmpS.Append(DB.RSField(rs, "SectionID").ToString());
                    }
                }
            }

            return tmpS.ToString();
        }

        public static string GetPollName(string PollID, string LocaleSetting)
        {
            string tmpS = string.Empty;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "select * from Poll  with (NOLOCK) where Pollid=" + PollID.ToString()))
                {
                    if (rs.Read())
                    {
                        tmpS = DB.RSFieldByLocale(rs, "Name", LocaleSetting);
                    }
                }
            }
            return tmpS;
        }

        public static bool ShowProductBuyButton(string ProductID)
        {
            bool tmp = true;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "select isnull(ShowBuyButton, 1) as ShowBuyButton from InventoryItemWebOption  with (NOLOCK) where ItemCode =" + DB.SQuote(ProductID.ToString()) +
                                      " AND WebSiteCode=" + DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode)))
                {
                    if (rs.Read())
                    {
                        tmp = DB.RSFieldBool(rs, "showbuybutton");
                    }
                }
            }
            return tmp;
        }

        public static bool ProductIsCallToOrder(string ProductID)
        {
            bool tmp = true;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "select isnull(IsCallToOrder,0) as IsCallToOrder from InventoryItemWebOption  with (NOLOCK) where ItemCode=" + DB.SQuote(ProductID.ToString()) +
                                      " AND WebSiteCode=" + DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode)))
                {
                    if (rs.Read())
                    {
                        tmp = DB.RSFieldBool(rs, "IsCallToOrder");
                    }
                }
            }
            return tmp;
        }

        public static int MultiShipMaxNumItemsAllowed()
        {
            int tmp = AppLogic.AppConfigUSInt("MultiShipMaxItemsAllowed");
            if (tmp == 0)
            {
                tmp = 25; // force a default
            }
            return tmp;
        }

        public static string GetVariantProductID(string VariantID)
        {
            string tmp = string.Empty;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "select Counter as productid from InventoryItem  with (NOLOCK) where Counter=" + VariantID.ToString()))
                {
                    if (rs.Read())
                    {
                        tmp = DB.RSField(rs, "ProductID");
                    }
                }
            }
            return tmp;
        }

        public static string GetCountryName(string CountryID)
        {
            string tmp = string.Empty;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "Select * from SystemCountry with (NOLOCK) WHERE UPPER(ISOCode)=" + DB.SQuote(CountryID)))
                {
                    if (rs.Read())
                    {
                        tmp = DB.RSField(rs, "CountryCode");
                    }
                }
            }
            return tmp;
        }

        public static string GetCountryTwoLetterISOCode(string CountryName)
        {
            string tmp = "US";
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, string.Format("SELECT ISOCode FROM SystemCountry with (NOLOCK) WHERE CountryCode = {0}", DB.SQuote(CountryName))))
                {
                    if (reader.Read())
                    {
                        tmp = DB.RSField(reader, "ISOCode");
                    }
                }
            }
            return tmp;
        }

        public static string GetCountryThreeLetterISOCode(string CountryName)
        {
            string tmp = "US";
            var ds = DB.GetDS("Select * from Country with (NOLOCK) order by DisplayOrder,Name", "Countries DataSet", AppLogic.CachingOn, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()));
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                if (CountryName.ToLower() == DB.RowField(row, "Name").ToLower())
                {
                    tmp = DB.RowField(row, "ThreeLetterISOCode");
                    break;
                }
            }
            ds.Dispose();
            return tmp;
        }

        public static void LogEvent(string CustomerID, int EventID, string parms)
        {
            if (!AppLogic.AppConfigBool("EventLoggingEnabled")) { return; }

            if (parms.Length == 0)
            {
                DB.ExecuteSQL("INSERT INTO EcommerceLOG_CustomerEvent(CustomerCode, EventID, Timestamp, Data) values(" +
                    DB.SQuote(CustomerID) + "," + EventID.ToString() + ",getdate(),NULL)");
            }
            else
            {
                DB.ExecuteSQL("INSERT INTO EcommerceLOG_CustomerEvent(CustomerCode, EventID, Timestamp, Data) values(" +
                    DB.SQuote(CustomerID.ToString()) + "," + EventID.ToString() + ",getdate()," + DB.SQuote(parms) + ")");
            }
        }

        public static bool ProductIsInCategory(string ProductID, string CategoryID)
        {
            bool IsInCat = false;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "select count(*) as N from productcategory  with (NOLOCK) where productid=" + ProductID.ToString() + " and categoryid=" + CategoryID.ToString()))
                {
                    rs.Read();
                    IsInCat = (DB.RSFieldInt(rs, "N") != 0);
                }
            }
            return IsInCat;
        }

        public static string GetProductCustomerLevels(string ProductID)
        {
            var tmpS = new StringBuilder(1000);
            if (ProductID.Length != 0)
            {
                using (var con = DB.NewSqlConnection())
                {
                    con.Open();
                    using (var rs = DB.GetRSFormat(con, "select * from productcustomerlevel  with (NOLOCK) where productid=" + ProductID.ToString()))
                    {
                        while (rs.Read())
                        {
                            if (tmpS.Length != 0)
                            {
                                tmpS.Append(",");
                            }
                            tmpS.Append(DB.RSField(rs, "CustomerLevelID").ToString());
                        }
                    }
                }
            }
            return tmpS.ToString();
        }

        public static string GetFirstProduct(string CategoryID, bool AllowKits, bool AllowPacks)
        {
            string id = string.Empty;
            if (CategoryID.Length != 0)
            {
                string sql = string.Format("exec EcommerceGetProducts @sortEntityName = 'category', @ProductFilterID = {0}", DB.SQuote(Customer.Current.ProductFilterID));
                var ds = DB.GetDS(sql, AppLogic.CachingOn, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()));
                if (ds.Tables[0].Rows.Count == 0)
                {
                    ds.Dispose();
                    return id;
                }
                id = ds.Tables[0].Rows[0]["ProductID"].ToString();
                ds.Dispose();
            }
            return id;
        }

        public static string GetEntityName(string EntityName, string EntityID, string LocaleSetting)
        {
            string tmpS = string.Empty;
            string origEntityName = EntityName;
            string tmpField;
            string tmpJoiningField;
            switch (EntityName.ToUpperInvariant())
            {
                case "CATEGORY":
                    EntityName = "SystemCategory";
                    tmpField = "ISNULL(b.Description,b.CategoryCode) as Name";
                    tmpJoiningField = "CategoryCode";
                    break;
                case "SECTION":
                case "DEPARTMENT":
                    EntityName = "InventorySellingDepartment";
                    tmpField = "ISNULL(b.Description,b.DepartmentCode) as Name";
                    tmpJoiningField = "DepartmentCode";
                    break;
                case "MANUFACTURER":
                    EntityName = "SystemManufacturer";
                    tmpField = "ISNULL(b.Description,b.ManufacturerCode) as Name";
                    tmpJoiningField = "ManufacturerCode";
                    break;
                case "ATTRIBUTE":
                    EntityName = "SystemItemAttributeSourceFilterValue";
                    tmpField = "ISNULL(b.SourceFilterDescription, b.SourceFilterName) as Name";
                    tmpJoiningField = "SourceFilterName";
                    break;
                default:
                    tmpField = "Name";
                    tmpJoiningField = "Name";
                    break;
            }

            string tmpSql = string.Empty;
            if (origEntityName.ToUpperInvariant() != "ATTRIBUTE")
            {
                tmpSql = "SELECT {0} FROM {1} a with (NOLOCK) INNER JOIN {1}Description b with (NOLOCK) ON a.{2}=b.{2} WHERE a.Counter={3} AND b.LanguageCode={4}";
            }
            else
            {
                tmpSql = "SELECT {0} FROM {1} a with (NOLOCK) INNER JOIN {1}Description b with (NOLOCK) ON a.{2}=b.{2} AND a.AttributeSourceFilterCode = b.AttributeSourceFilterCode WHERE a.Counter={3} AND b.LanguageCode={4}";
            }

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, tmpSql, tmpField, EntityName, tmpJoiningField, EntityID.ToString(), DB.SQuote(((InterpriseSuiteEcommercePrincipal)HttpContext.Current.User).ThisCustomer.LanguageCode)))
                {
                    if (rs.Read())
                    {
                        tmpS = DB.RSFieldByLocale(rs, "Name", LocaleSetting);
                    }
                }
            }

            return tmpS;
        }

        public static string GetFirstProductEntity(EntityHelper EntityHelper, string ProductID, bool ForProductBrowser, string LocaleSetting)
        {
            string tmpS = EntityHelper.GetObjectEntities(ProductID, ForProductBrowser);
            if (tmpS.Length == 0)
            {
                return string.Empty;
            }
            var ss = tmpS.Split(',');
            string result = string.Empty;
            try
            {
                result = EntityHelper.GetEntityName(ss[0], LocaleSetting);
            }
            catch { }
            return result;
        }

        public static string GetFirstProductEntityID(EntityHelper EntityHelper, string ProductID, bool ForProductBrowser)
        {
            string tmpS = EntityHelper.GetObjectEntities(ProductID, ForProductBrowser);
            if (tmpS.Length == 0)
            {
                return string.Empty;
            }
            var ss = tmpS.Split(',');
            string tmp = string.Empty;
            try
            {
                tmp = ss[0];
            }
            catch { }
            return tmp;
        }

        public static string GetProductName(string ProductID, string LocaleSetting)
        {
            string tmpS = string.Empty;
            if (ProductID.Length != 0)
            {
                using (var con = DB.NewSqlConnection())
                {
                    con.Open();
                    using (var rs = DB.GetRSFormat(con, string.Format("SELECT ItemCode, ItemName, ItemDescription FROM EcommerceViewProduct with (NOLOCK) WHERE ItemCode = {0} AND ShortString = {1} AND WebSiteCode = {2}",
                                                                                    DB.SQuote(ProductID), DB.SQuote(LocaleSetting), DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode))))
                    {
                        if (rs.Read())
                        {
                            if (DB.RSField(rs, "ItemDescription").ToString() != string.Empty)
                            {
                                tmpS = DB.RSField(rs, "ItemDescription");
                            }
                            else
                            {
                                tmpS = DB.RSField(rs, "ItemName");
                            }
                        }
                    }
                }
            }
            return tmpS;
        }

        public static string GetProductXmlPackage(string ProductID)
        {
            string tmpS = string.Empty;
            if (ProductID.Length != 0)
            {
                using (var con = DB.NewSqlConnection())
                {
                    con.Open();
                    using (var rs = DB.GetRSFormat(con, "select XmlPackage from product  with (NOLOCK) where productid=" + ProductID.ToString()))
                    {
                        if (rs.Read())
                        {
                            tmpS = DB.RSField(rs, "XmlPackage").ToLowerInvariant();
                        }
                    }
                }
            }
            return tmpS;
        }

        public static string GetItemCodeByCounter(int? counter)
        {
            string _itemCode = string.Empty;
            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader dr = DB.GetRSFormat(con, "SELECT ItemCode FROM InventoryItem with (NOLOCK) WHERE Counter={0}", counter))
                {
                    if (dr.Read())
                    {
                        _itemCode = DB.RSField(dr, "ItemCode");
                    }
                }
            }
            return _itemCode;
        }

        public static ECommerceProductInfoView GetProductInfoViewForShowProduct(string itemCode, string localeSettings, string userCode, string websiteCode, string dateTimeStringFromDB, string productFilterId, string contactCode)
        {
            ECommerceProductInfoView eCommerceProductInfoView = null;
            string query = string.Format("exec eCommerceProductInfo @ItemCode = {0}, @LanguageCode = {1}, @UserCode = {2}, @WebSiteCode = {3}, @CurrentDate = {4}, @ProductFilterID = {5}, @ContactCode = {6}",
                                          itemCode, localeSettings, userCode, websiteCode, dateTimeStringFromDB, productFilterId, contactCode);

            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var dr = DB.GetRSFormat(con, query))
                {

                    if (!dr.Read())
                    {
                        dr.Close();
                        return eCommerceProductInfoView;
                    }

                    eCommerceProductInfoView = new ECommerceProductInfoView
                    {
                        Counter = DB.RSFieldInt(dr, "Counter"),
                        ItemCode = DB.RSField(dr, "ItemCode"),
                        ItemName = DB.RSField(dr, "ItemName"),
                        ItemDescription = DB.RSField(dr, "ItemDescription"),
                        CheckOutOption = DB.RSFieldBool(dr, "CheckOutOption"),
                        RequiresRegistration = DB.RSFieldBool(dr, "RequiresRegistration"),
                        SETitle = DB.RSField(dr, "SETitle"),
                        SEDescription = DB.RSField(dr, "SEDescription"),
                        SEKeywords = DB.RSField(dr, "SEKeywords"),
                        SENoScript = DB.RSField(dr, "SENoScript"), 
                        IsAKit = DB.RSFieldInt(dr, "IsAKit"),
                        IsMatrix = DB.RSFieldInt(dr, "IsMatrix"),
                        XmlPackage = DB.RSField(dr, "XmlPackage"),
                        MobileXmlPackage = DB.RSField(dr, "MobileXmlPackage"),
                        IsCBN = DB.RSFieldBool(dr, "IsCBN"),
                        ItemType = DB.RSField(dr, "ItemType"),
                        WebDescription = DB.RSField(dr, "WebDescription"),
                        Summary = DB.RSField(dr, "Summary"),
                        Warranty = DB.RSField(dr, "Warranty"),
                        ExpectedShippingDate = DB.RSFieldDateTime(dr, "ExpShipingDate")
                    };
                    dr.Close();
                }
            }
            return eCommerceProductInfoView;
        }

        //strongly typed
        public static IEnumerable<int> GetProductEntityList(String itemCode, String EntityName)
        {
            var lst = new List<int>();
            if (EntityName.Length == 0)
            {
                EntityName = EntityDefinitions.readonly_CategoryEntitySpecs.m_EntityName;
            }

            using (DataSet ds = DB.GetDS(string.Format("exec eCommerceGetProductEntityList @ItemCode = {0}, @EntityName = {1}, @WebSiteCode = {2}, @LanguageCode = {3}", DB.SQuote(itemCode), DB.SQuote(EntityName), DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode), DB.SQuote(Customer.Current.LanguageCode)), false, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes())))
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        lst.Add(DB.RowFieldInt(row, EntityName + "ID"));
                    }
                }
            }

            return lst;
        }

        #region "Photo Resize Routines"

        /// <summary>
        /// SplitResizeConfig 
        /// This routine reads the necessary Image Resize information from the Application Configuration into a string,
        /// splits it and returns a Hashtable object.
        /// </summary>
        /// <param name="EntityOrObjectName"></param>
        /// <param name="img_SizeType"></param>
        /// <returns></returns>
        public static Hashtable SplitResizeConfig(string EntityOrObjectName, string img_SizeType)
        {
            char[] trimChars = { ' ', ';' };

            string imgAppConfigParam = AppConfig(EntityOrObjectName + "Img_" + img_SizeType).TrimEnd(trimChars);

            var m_mapEntries = new Hashtable();

            // Split the input string
            string[] arEntries = imgAppConfigParam.Split(';');
            for (int i = 0; i < arEntries.Length; ++i)
            {
                // Split this entry in to key and value
                string[] arPieces = arEntries[i].Split(':');

                try
                {
                    if (arPieces.Length > 1)
                    {
                        // Add this key/value pair (trimmed and lowercase) to our map
                        m_mapEntries[arPieces[0].Trim().ToLower()] = arPieces[1].Trim().ToLower();
                    }
                }
                catch { }
            }
            return m_mapEntries;
        }

        /// <summary>
        /// SplitOtherConfig
        /// This routine reads related Image Resize information, that is not handled by SplitResizeConfig, from the Application Configuration into a string,
        /// splits it and returns a Hashtable object.
        /// </summary>
        /// <param name="configValue"></param>
        /// <returns></returns>
        public static Hashtable SplitOtherConfig(string configValue)
        {
            char[] trimChars = { ' ', ';' };

            string imgAppConfigParam = AppConfig(configValue).TrimEnd(trimChars);
            var m_mapEntries = new Hashtable();

            // Split the input string
            string[] arEntries = imgAppConfigParam.Split(';');
            for (int i = 0; i < arEntries.Length; ++i)
            {
                // Split this entry in to key and value
                string[] arPieces = arEntries[i].Split(':');

                try
                {
                    if (arPieces.Length > 1)
                    {
                        // Add this key/value pair (trimmed and lowercase) to our map
                        m_mapEntries[arPieces[0].Trim().ToLower()] = arPieces[1].Trim().ToLower();
                    }
                }
                catch { }

            }

            return m_mapEntries;
        }

        /// <summary>
        /// ResizeEntityOrObject
        /// This routine prepares the image for resizing by fetching the Image Resize info using SplitResizeConfig.
        /// </summary>
        /// <param name="EntityOrObjectName"></param>
        /// <param name="ImageToResize"></param>
        /// <param name="img_fName"></param>
        /// <param name="img_SizeType"></param>
        /// <param name="img_ContentType"></param>
        /// <param name="disableImageResizing">If set to true, then no image resizing will occur</param>
        public static void ResizeEntityOrObject(string EntityOrObjectName, System.Drawing.Image ImageToResize, string img_fName, string img_SizeType, string img_ContentType, bool disableImageResizing)
        {
            ResizeEntityOrObject(EntityOrObjectName, ImageToResize, img_fName, img_SizeType,img_ContentType, disableImageResizing, string.Empty);
        }

        public static void ResizeEntityOrObject(string EntityOrObjectName, System.Drawing.Image ImageToResize, string img_fName, string img_SizeType, string img_ContentType, bool disableImageResizing, string imagePath = "")
        {
            System.Drawing.Image tempImage = ImageToResize;
            string imgExt = string.Empty;
            switch (img_ContentType)
            {
                case "image/png":
                    imgExt = ".png";
                    break;
                case "image/jpeg":
                    imgExt = ".jpg";
                    break;
                case "image/gif":
                    imgExt = ".gif";
                    break;
            }

            string img_FileName = string.Empty;
            if (imagePath != string.Empty)
            {
                img_FileName = imagePath;
            }
            else
            {
                img_FileName = GetImagePath(EntityOrObjectName, img_SizeType, true) + img_fName + imgExt;
            }

            var splitConfig = new Hashtable();
            switch (EntityOrObjectName.ToUpperInvariant())
            {
                case "CATEGORY":
                    splitConfig = SplitResizeConfig("Category", img_SizeType);
                    splitConfig.Add("resize", true);
                    break;
                case "MANUFACTURER":
                    splitConfig = SplitResizeConfig("Manufacturer", img_SizeType);
                    splitConfig.Add("resize", true);
                    break;
                case "SECTION":
                case "DEPARTMENT":
                    splitConfig = SplitResizeConfig("Department", img_SizeType);
                    splitConfig.Add("resize", true);
                    break;
                case "PRODUCT":
                    splitConfig = SplitResizeConfig("Product", img_SizeType);
                    break;
                case "ATTRIBUTE":
                    splitConfig = SplitResizeConfig("Product", img_SizeType);
                    break;
                default:
                    return;
            }
            ResizePhoto(splitConfig, tempImage, img_FileName, img_SizeType, img_ContentType, disableImageResizing);
        }

        /// <summary>
        /// ResizePhoto
        /// Actual image resizing and tweaking is done in this routine. Invoked by ResizeEntityOrObject.
        /// </summary>
        /// <param name="configValues"></param>
        /// <param name="origPhoto"></param>
        /// <param name="img_fName"></param>
        /// <param name="img_SizeType"></param>
        /// <param name="img_ContentType"></param>
        /// <param name="disableImageResizing">If set to true, then no image resizing will occur</param>
        public static void ResizePhoto(Hashtable configValues, System.Drawing.Image origPhoto, string img_fName, string img_SizeType, string img_ContentType, bool disableImageResizing)
        {
            bool resizeMe = AppConfigBool("UseImageResize"); //set this to false if the image editor is ready, because the editor will handle the resizing
            if (configValues.ContainsKey("resize") && configValues["resize"].ToString().ToLower() == "false")
            {
                resizeMe = false;
            }
            else if (configValues.ContainsKey("resize") && configValues["resize"].ToString().ToLower() == "true")
            {
                resizeMe = true;
            }

            if (disableImageResizing)
            {
                resizeMe = false;
            }

            if (resizeMe)
            {
                int resizedWidth = AppConfigNativeInt("DefaultWidth_" + img_SizeType);
                int resizedHeight = AppConfigNativeInt("DefaultHeight_" + img_SizeType);

                int resizedQuality = AppConfigNativeInt("DefaultQuality");

                string stretchMe = AppConfig("DefaultStretch");
                string cropMe = AppConfig("DefaultCrop");
                string cropV = AppConfig("DefaultCropVertical");
                string cropH = AppConfig("DefaultCropHorizontal");
                string fillColor = AppConfig("DefaultFillColor");

                int sourceWidth = origPhoto.Width;
                int sourceHeight = origPhoto.Height;
                int sourceX = 0;
                int sourceY = 0;
                // we will extend 2 pixels on all sides to avoid the border bug
                // we could use InterpolationMode.NearestNeighbor instead of
                // InterpolationMode.HighQualityBicubic but not without sacrificing quality
                int destX = -2;
                int destY = -2;

                float nPercent = 0;
                float nPercentW = 0;
                float nPercentH = 0;

                int destWidth = 0;
                int destHeight = 0;

                if (configValues.ContainsKey("width"))
                {
                    //added checking so that when "productimg" appconfigs is 0
                    //it will get the values from default appconfigs size
                    int configValueWidth = Int32.Parse(configValues["width"].ToString());

                    if (configValueWidth == 0)
                    {
                        resizedWidth = AppConfigNativeInt("DefaultWidth_" + img_SizeType);
                    }
                    else
                    {
                        if (CommonLogic.IsInteger(configValues["width"].ToString()))
                        {
                            resizedWidth = Int32.Parse(configValues["width"].ToString());
                        }
                    }
                }
                if (configValues.ContainsKey("height"))
                {
                    //added checking so that when "productimg" appconfigs contains is 0
                    //it will get the values from default appconfigs size
                    int configValueHeight = Int32.Parse(configValues["height"].ToString());

                    if (configValueHeight == 0)
                    {
                        resizedHeight = AppConfigNativeInt("DefaultHeight_" + img_SizeType);
                    }
                    else
                    {
                        if (CommonLogic.IsInteger(configValues["height"].ToString()))
                        {
                            resizedHeight = Int32.Parse(configValues["height"].ToString());
                        }
                    }
                }
                if (configValues.ContainsKey("quality"))
                {
                    if (CommonLogic.IsInteger(configValues["quality"].ToString()))
                    {
                        resizedQuality = Int32.Parse(configValues["quality"].ToString());
                    }
                }
                if (configValues.ContainsKey("stretch"))
                {
                    stretchMe = configValues["stretch"].ToString();
                }
                if (configValues.ContainsKey("fill"))
                {
                    fillColor = configValues["fill"].ToString();
                }
                if (configValues.ContainsKey("crop"))
                {
                    cropMe = configValues["crop"].ToString();
                    if (cropMe == "true")
                    {
                        if (configValues.ContainsKey("cropv"))
                        {
                            cropV = configValues["cropv"].ToString();
                        }
                        if (configValues.ContainsKey("croph"))
                        {
                            cropH = configValues["croph"].ToString();
                        }
                    }
                }

                if (resizedWidth < 1 || resizedHeight < 1)
                {
                    resizedWidth = origPhoto.Width;
                    resizedHeight = origPhoto.Height;
                }


                if (cropMe == "true")
                {
                    string AnchorUpDown = cropV;
                    string AnchorLeftRight = cropH;
                    nPercentW = ((float)resizedWidth / (float)sourceWidth);
                    nPercentH = ((float)resizedHeight / (float)sourceHeight);

                    if (nPercentH < nPercentW)
                    {
                        nPercent = nPercentW;
                        switch (AnchorUpDown)
                        {
                            case "top":
                                destY = -2;
                                break;
                            case "bottom":
                                destY = (int)(resizedHeight - (sourceHeight * nPercent));
                                break;
                            case "center":
                            default:
                                destY = (int)((resizedHeight - (sourceHeight * nPercent)) / 2) - 2;
                                break;
                        }
                    }
                    else
                    {
                        nPercent = nPercentH;
                        switch (AnchorLeftRight.ToUpper())
                        {
                            case "left":
                                destX = 0;
                                break;
                            case "right":
                                destX = (int)(resizedWidth - (sourceWidth * nPercent));
                                break;
                            case "middle":
                            default:
                                destX = (int)((resizedWidth - (sourceWidth * nPercent)) / 2) - 2;
                                break;
                        }
                    }
                }
                else
                {
                    nPercentW = ((float)resizedWidth / (float)sourceWidth);
                    nPercentH = ((float)resizedHeight / (float)sourceHeight);

                    if (nPercentH < nPercentW)
                    {
                        nPercent = nPercentH;
                        destX = (int)((resizedWidth - (sourceWidth * nPercent)) / 2);
                    }
                    else
                    {
                        nPercent = nPercentW;
                        destY = (int)((resizedHeight - (sourceHeight * nPercent)) / 2) - 2;
                    }
                }
                // let's account for the extra pixels we left to avoid the borderbug here
                // some distortion will occur...but it should be unnoticeable
                if (stretchMe == "false" && origPhoto.Width < resizedWidth && origPhoto.Height < resizedHeight)
                {
                    destWidth = origPhoto.Width;
                    destHeight = origPhoto.Height;
                    destX = (int)((resizedWidth / 2) - (origPhoto.Width / 2));
                    destY = (int)((resizedHeight / 2) - (origPhoto.Height / 2));
                }
                else if (stretchMe == "true")
                {
                    destWidth = (int)Math.Ceiling(sourceWidth * nPercent) + 4;
                    destHeight = (int)Math.Ceiling(sourceHeight * nPercent) + 4;
                }
                else
                {
                    destWidth = (int)Math.Ceiling(sourceWidth * nPercent) + 4;
                    destHeight = (int)Math.Ceiling(sourceHeight * nPercent) + 4;
                }

                Bitmap resizedPhoto = new Bitmap(resizedWidth, resizedHeight, PixelFormat.Format24bppRgb);
                resizedPhoto.SetResolution(origPhoto.HorizontalResolution, origPhoto.VerticalResolution);

                Graphics grPhoto = Graphics.FromImage(resizedPhoto);

                Color clearColor = new Color();
                try
                {
                    clearColor = System.Drawing.ColorTranslator.FromHtml(fillColor);
                }
                catch
                {
                    clearColor = Color.White;
                }
                grPhoto.Clear(clearColor);

                if (resizedQuality > 100 || resizedQuality < 1)
                {
                    resizedQuality = 100;
                }

                // Encoder parameter for image quality 
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, resizedQuality);

                if (img_ContentType == "image/gif")
                    img_ContentType = "image/jpeg";
                // Image codec 
                ImageCodecInfo imgCodec = GetEncoderInfo(img_ContentType);

                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;

                grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
                grPhoto.DrawImage(origPhoto,
                    new Rectangle(destX, destY, destWidth, destHeight),
                    new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                    GraphicsUnit.Pixel);

                grPhoto.Dispose();

                using (FileStream outStream = new FileStream(img_fName, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    resizedPhoto.Save(outStream, imgCodec, encoderParams);
                }
            }
            else
            {
                using (FileStream outStream = new FileStream(img_fName, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    ImageFormat format = null;
                    switch (img_ContentType)
                    {
                        case "image/jpeg":
                            format = ImageFormat.Jpeg;
                            break;

                        case "image/gif":
                            format = ImageFormat.Gif;
                            break;

                        case "image/png":
                            format = ImageFormat.Png;
                            break;
                    }

                    origPhoto.Save(outStream, format);
                }
            }
        }

        /// <summary>
        /// CreateOthersFromLarge
        /// This routine dynamically creates "icon" and "medium" -size images based on the given "large" image. 
        /// Checks and relies on two AppConfig: LargeCreatesOthers and LargeOverwritesOthers for its use.
        /// </summary>
        /// <param name="EntityOrObjectName"></param>
        /// <param name="origPhoto"></param>
        /// <param name="img_FileName"></param>
        /// <param name="img_ContentType"></param>
        /// <param name="isMultiImage"></param>
        /// <param name="disableImageResizing">If set to true, then no image resizing will occur</param>
        public static void CreateOthersFromLarge(string EntityOrObjectName, System.Drawing.Image origPhoto, string img_FileName, string img_ContentType, bool isMultiImage, bool disableImageResizing)
        {
            System.Drawing.Image origImage = origPhoto;

            bool largeCreates = false;
            bool largeOverwrites = false;
            bool globalCreate = AppConfigBool("LargeCreatesOthers");
            bool globalOverwrite = AppConfigBool("LargeOverwritesOthers");

            string localCreate = string.Empty;
            string localOverwrite = string.Empty;

            Hashtable configValues = SplitResizeConfig(EntityOrObjectName, "large");

            if (configValues.ContainsKey("largecreates"))
            {
                localCreate = configValues["largecreates"].ToString();
            }
            if (configValues.ContainsKey("largeoverwrites"))
            {
                localOverwrite = configValues["largeoverwrites"].ToString();
            }

            if (localCreate == "false")
                largeCreates = false;
            else if (localCreate == "true")
                largeCreates = true;
            else
                largeCreates = globalCreate;

            if (localOverwrite == "false")
                largeOverwrites = false;
            else if (localOverwrite == "true")
                largeOverwrites = true;
            else
                largeOverwrites = globalOverwrite;

            if (!largeCreates) { return; }

            if (largeOverwrites && !disableImageResizing)
            {
                // delete any smaller image files first
                try
                {
                    foreach (string ss in CommonLogic.SupportedImageTypes)
                    {
                        System.IO.File.Delete(GetImagePath(EntityOrObjectName, "icon", true) + img_FileName + ss);
                        System.IO.File.Delete(GetImagePath(EntityOrObjectName, "medium", true) + img_FileName + ss);
                        System.IO.File.Delete(GetImagePath(EntityOrObjectName, "micro", true) + img_FileName + ss);
                    }
                }
                catch { }
                ResizeEntityOrObject(EntityOrObjectName, origImage, img_FileName, "icon", img_ContentType, disableImageResizing);

                ResizeEntityOrObject(EntityOrObjectName, origImage, img_FileName, "medium", img_ContentType, disableImageResizing);
                if (AppLogic.AppConfigBool("MultiMakesMicros"))
                {
                    MakeMicroPic(img_FileName, origImage);
                }

                MakeMiniCartPic(img_FileName, origImage);
            }
            else
            {
                bool iconExists = false;
                bool mediumExists = false;
                foreach (string ss in CommonLogic.SupportedImageTypes)
                {
                    if (CommonLogic.FileExists(GetImagePath(EntityOrObjectName, "icon", true) + img_FileName + ss))
                    {
                        iconExists = true;
                    }
                    if (CommonLogic.FileExists(GetImagePath(EntityOrObjectName, "medium", true) + img_FileName + ss))
                    {
                        mediumExists = true;
                    }
                }
                if (!iconExists)
                {
                    ResizeEntityOrObject(EntityOrObjectName, origImage, img_FileName, "icon", img_ContentType, disableImageResizing);
                }
                if (!mediumExists)
                {
                    ResizeEntityOrObject(EntityOrObjectName, origImage, img_FileName, "medium", img_ContentType, disableImageResizing);
                    if (AppLogic.AppConfigBool("MultiMakesMicros"))
                    {
                        MakeMicroPic(img_FileName, origImage);
   
                    }

                    MakeMiniCartPic(img_FileName, origImage);

                }
            }
        }

        /// <summary>
        /// GetEncoderInfo
        /// Get image codecs for all image formats and returns correct image codec based on the given MimeType.
        /// </summary>
        /// <param name="resizeMimeType"></param>
        /// <returns></returns>
        private static ImageCodecInfo GetEncoderInfo(string resizeMimeType)
        {
            // Get image codecs for all image formats 
            var codecs = ImageCodecInfo.GetImageEncoders();
            // Find the correct image codec 
            for (int i = 0; i < codecs.Length; i++)
            {
                if (codecs[i].MimeType == resizeMimeType)
                    return codecs[i];
            }
            return null;
        }

        /// <summary>
        /// ResizeForSwatch
        /// Resizes a given image for Swatch.
        /// </summary>
        /// <param name="origPhoto"></param>
        /// <param name="swatchWidth"></param>
        /// <param name="swatchHeight"></param>
        /// <returns></returns>
        public static System.Drawing.Image ResizeForSwatch(System.Drawing.Image origPhoto, int swatchWidth, int swatchHeight)
        {
            int resizedWidth = swatchWidth;
            int resizedHeight = swatchHeight;
            int sourceWidth = origPhoto.Width;
            int sourceHeight = origPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;

            int destX = -2;
            int destY = -2;
            float nPercent = 0;
            float nPercentW = ((float)resizedWidth / (float)sourceWidth);
            float nPercentH = ((float)resizedHeight / (float)sourceHeight);
            int destWidth = 0;
            int destHeight = 0;

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                destY = (int)((resizedHeight - (sourceHeight * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentH;
                destX = (int)((resizedWidth - (sourceWidth * nPercent)) / 2) - 2;
            }

            destWidth = (int)Math.Ceiling(sourceWidth * nPercent) + 4;
            destHeight = (int)Math.Ceiling(sourceHeight * nPercent) + 4;

            var resizedPhoto = new Bitmap(resizedWidth, resizedHeight, PixelFormat.Format24bppRgb);

            var grPhoto = Graphics.FromImage(resizedPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            grPhoto.DrawImage(origPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            origPhoto.Dispose();
            return resizedPhoto;
        }

        /// <summary>
        /// ResizeForMicro
        /// Resizes a given image for Micro. 
        /// </summary>
        /// <param name="origPhoto"></param>
        /// <param name="newImg_fName"></param>
        /// <param name="microWidth"></param>
        /// <param name="microHeight"></param>
        public static void ResizeForMicro(System.Drawing.Image origPhoto, string newImg_fName, int microWidth, int microHeight)
        {
            ImageHelper.ResizeCustomImage(origPhoto, newImg_fName, microWidth, microHeight);
        }

        /// <summary>
        /// MakeMicroPic 
        /// Actual micro image creation is done in this routine. Invoked by ResizeForMicro.
        /// </summary>
        /// <param name="img_FileName"></param>
        /// <param name="origPhoto"></param>
        public static void MakeMicroPic(string img_FileName, System.Drawing.Image origPhoto)
        {
            //if micro folder does not exist, just create it  
            var microFolder = new DirectoryInfo(AppLogic.GetImagePath("Product", "micro", true));
            if (!microFolder.Exists)
            {
                microFolder.Create();
            }

            var splitConfig = SplitOtherConfig("MicroStyle");

            int microWidth = 40;
            int microHeight = 40;

            string microMIME = string.Empty;

            if (splitConfig.ContainsKey("width"))
                microWidth = Int32.Parse(splitConfig["width"].ToString());
            if (splitConfig.ContainsKey("height"))
                microHeight = Int32.Parse(splitConfig["height"].ToString());
            if (splitConfig.ContainsKey("mime"))
                microMIME = splitConfig["mime"].ToString();

            if (microHeight < 1)
                microHeight = 40;
            if (microWidth < 1)
                microWidth = 40;

            switch (microMIME)
            {
                case "png":
                    microMIME = ".png";
                    break;
                case "jpg":
                default:
                    microMIME = ".jpg";
                    break;
            }

            string newImageName = AppLogic.GetImagePath("Product", "micro", true) + img_FileName + microMIME;

            ImageHelper.ResizeCustomImage(origPhoto, newImageName, microWidth, microHeight);

        }

        /// <summary>
        /// MakeMicroPic 
        /// Actual micro image creation is done in this routine. Invoked by ResizeForMicro.
        /// </summary>
        /// <param name="img_FileName"></param>
        /// <param name="origPhoto"></param>
        public static void MakeMiniCartPic(string img_FileName, System.Drawing.Image origPhoto, string extension = "")
        {
            //if micro folder does not exist, just create it  
            var minicartFolder = new DirectoryInfo(AppLogic.GetImagePath("Product", "minicart", true));
            if (!minicartFolder.Exists)
            {
                minicartFolder.Create();
            }

            var splitConfig = SplitOtherConfig("MiniCartStyle");

            int microWidth = 50;
            int microHeight = 50;

            string microMIME = string.Empty;

            if (splitConfig.ContainsKey("width"))
                microWidth = Int32.Parse(splitConfig["width"].ToString());
            if (splitConfig.ContainsKey("height"))
                microHeight = Int32.Parse(splitConfig["height"].ToString());
            if (splitConfig.ContainsKey("mime"))
                microMIME = splitConfig["mime"].ToString();

            if (microHeight < 1)
                microHeight = 50;
            if (microWidth < 1)
                microWidth = 50;

            if (extension.IsNullOrEmptyTrimmed())
            {
                switch (microMIME)
                {
                    case "png":
                        microMIME = ".png";
                        break;
                    case "jpg":
                    default:
                        microMIME = ".jpg";
                        break;
                }
            }
            else
            {
                microMIME = extension;
            }

            string newImageName = AppLogic.GetImagePath("Product", "minicart", true) + img_FileName + microMIME;
            ImageHelper.ResizeCustomImage(origPhoto, newImageName, microWidth, microHeight);

        }

        /// <summary>
        /// MakeMobilePc
        /// Actual Mobile image creation is done in this routine.
        /// </summary>
        /// <param name="imgEntityType"></param>
        /// <param name="imgFileName"></param>
        /// <param name="origPhoto"></param>
        /// <param name="fileExt"></param>
        public static void MakeMobilePic(string imgEntityType, string imgFileName, System.Drawing.Image origPhoto, string fileExt, string customDirectory = "")
        {
            //if micro folder does not exist, just create it
            var mobilePicFolder = new DirectoryInfo(AppLogic.GetMobileImagePath(imgEntityType, (customDirectory.IsNullOrEmptyTrimmed() ? "mobile" : customDirectory), true));

            if (!mobilePicFolder.Exists) { mobilePicFolder.Create(); }

            int? defaultWidth;
            int? defaultHeight;
            string[] imageSizeArr = null;
            string configValue = string.Empty;
            string mime = string.Empty;

            if (customDirectory == "micro")
            {
                defaultWidth = 40;
                defaultHeight = 40;
                configValue = AppConfig("MicroStyle");
            }
            else
            {
                defaultWidth = 79;
                defaultHeight = 101;
                configValue = AppConfig("MobileImageStyle");
            }

            imageSizeArr = configValue.Split(';')
                                        .Where(item => !item.IsNullOrEmptyTrimmed())
                                        .ToArray();    

            if (imageSizeArr.Length > 1)
            {
                var hashTable = new Hashtable();
                imageSizeArr.ForEach(val => hashTable.Add(val.Split(':')[0], val.Split(':')[1]));

                defaultWidth = hashTable["width"].TryParseInt();
                defaultHeight = hashTable["height"].TryParseInt();
                if (hashTable.ContainsKey("mime")) mime = hashTable["mime"].ToString();
            }

            if (!defaultWidth.HasValue || defaultWidth < 1) { defaultWidth = 79; }
            if (!defaultHeight.HasValue || defaultHeight < 1) { defaultHeight = 101; }
            if (mime.IsNullOrEmptyTrimmed()) { mime = fileExt; }

            switch (mime)
            {
                case "gif":
                    mime = ".gif";
                    break;
                case "png":
                    mime = ".png";
                    break;
                case "jpg":
                default:
                    mime = ".jpg";
                    break;
            }

            string newImageName = mobilePicFolder + imgFileName + mime;
            ImageHelper.ResizeCustomImage(origPhoto, newImageName, defaultWidth.Value, defaultHeight.Value);
        }

        #endregion

        public static string GetImagePath(string EntityOrObjectName, string size, bool fullPath)
        {
            string path = "images/" + EntityOrObjectName + "/" + ((size.Length > 0) ? size.ToLower() : string.Empty) + "/";
            if (fullPath)
            {
                path = CommonLogic.SafeMapPath(path);
            }
            return path;
        }

        public static string GetMobileImagePath(string entityName, string size, bool fullPath)
        {
            string path = "mobile/images/" + entityName + "/" + ((size.Length > 0) ?  size.ToLower() : string.Empty) + "/";
            if (fullPath) 
            { 
                path = CommonLogic.SafeMapPath(path); 
            }
            return path;
        }

        private static string GetMobileSwatchImagePath(string entityName, bool fullPath)
        {
            string path = "mobile/images/product/swatch/";
            if (fullPath)
            {
                path = CommonLogic.SafeMapPath(path);
            }
            return path;
        }

        public static string LookupImage(string EntityOrObjectName, string ID, string ImgSize, int SkinID, string LocaleSetting)
        {
            string EONU = EntityOrObjectName.ToUpperInvariant();
            string FN = string.Empty;
            if (FN.Length == 0)
            {
                FN = ID.ToString();
            }

            string Image1URL = string.Empty;

            Image1URL = LocateImageURL(FN, EONU, ImgSize, LocaleSetting);
            if (Image1URL.Length == 0 && (ImgSize == "icon" || ImgSize == "medium"))
            {
                Image1URL = AppLogic.NoPictureImageURL(ImgSize == "icon", SkinID, LocaleSetting);
            }
            return Image1URL;
        }

        public static string LookupImage(string EntityOrObjectName, string ID, string ImageFileNameOverride, string SKU, string ImgSize, int SkinID, string LocaleSetting)
        {
            string EONU = EntityOrObjectName.ToUpperInvariant();
            string FN = string.Empty;
            bool OverridesEnabled = AppLogic.AppConfigBool("ImageFilenameOverrideEnabled") && (EONU == "PRODUCT" || EONU == "VARIANT" || EONU == "DOCUMENT" || EONU == "PRODUCTVARIANT" || EntityDefinitions.LookupSpecs(EONU) != null);
            if (OverridesEnabled)
            {
                FN = ImageFileNameOverride;
            }
            if (FN.Length == 0 && EONU == "PRODUCT")
            {
                FN = SKU;
            }
            if (FN.Length == 0)
            {
                FN = ID.ToString();
            }
            string Image1 = string.Empty;
            string Image1URL = InterpriseHelper.GetImage(FN, ImgSize, SkinID, LocaleSetting, false);
            if (Image1URL.Length == 0 && (ImgSize == "icon" || ImgSize == "medium"))
            {
                Image1URL = AppLogic.NoPictureImageURL(ImgSize == "icon", SkinID, LocaleSetting);
                if (Image1URL.Length != 0)
                {
                    Image1 = CommonLogic.SafeMapPath(Image1URL);
                }
            }
            return Image1URL;
        }


        public void PostLog(string XmlFragment)
        {
            string xactFileName = string.Format(@"Soap{0}.xml", DateTime.UtcNow.ToString("yyyyMM"));
            string xactLogName = string.Format(@"Soap{0}.log", DateTime.UtcNow.ToString("yyyyMM"));

            string xactFile = CommonLogic.SafeMapPath("images" + xactFileName);
            string xactLog = CommonLogic.SafeMapPath("images" + xactLogName);

            StreamWriter sw = null;

            //Create the containing xml file if the Date changes.
            if (!File.Exists(xactFile))
            {
                sw = File.CreateText(xactFile);
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                sw.WriteLine(string.Format("<!DOCTYPE SoapLogs [<!ENTITY soaplog SYSTEM \"{0}\"> ]>", xactLogName));
                sw.WriteLine("<SoapLog>&soaplog;</SoapLog>");
                sw.Close();
            }
            HttpContext.Current.Application.Lock();
            sw = File.AppendText(xactLog);
            sw.WriteLine(XmlFragment);
            sw.Close();
            HttpContext.Current.Application.UnLock();
        }

        public static string ReadCookie(string name)
        {
            if (HttpContext.Current.Response.Cookies.AllKeys.Contains(name))
            {
                var cookie = HttpContext.Current.Response.Cookies[name];
                return cookie.Value;
            }

            if (HttpContext.Current.Request.Cookies.AllKeys.Contains(name))
            {
                var cookie = HttpContext.Current.Request.Cookies[name];
                return cookie.Value;
            }
            return null;
        }

        public static void SetCookie(string cookieName, string cookieVal)
        {
            try
            {
                HttpContext.Current.Response.Cookies[cookieName].Value = cookieVal;
            }
            catch
            { }
        }

        public static void SetCookie(string cookieName, string cookieVal, TimeSpan ts)
        {
            try
            {
                HttpCookie cookie = new HttpCookie(cookieName);
                cookie.Value = HttpContext.Current.Server.UrlEncode(cookieVal);
                DateTime dt = DateTime.Now;
                cookie.Expires = dt.Add(ts);
                if (AppLogic.OnLiveServer())
                {
                    cookie.Domain = AppLogic.LiveServer();
                }
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            catch
            { }
        }

        public static void SetSessionCookie(string cookieName, string cookieVal)
        {
            try
            {
                HttpCookie cookie = new HttpCookie(cookieName);
                cookie.Value = HttpContext.Current.Server.UrlEncode(cookieVal);
                if (AppLogic.OnLiveServer())
                {
                    cookie.Domain = AppLogic.LiveServer();
                }
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            catch
            { }
        }

        /// <summary>
        /// Clears the cookie information
        /// </summary>
        /// <param name="cookieName"></param>
        public static void RemoveCookie(string cookieName)
        {
            try
            {
                HttpCookie cookie = new HttpCookie(cookieName);
                cookie.Value = HttpContext.Current.Server.UrlEncode(string.Empty);
                if (AppLogic.OnLiveServer())
                {
                    cookie.Domain = AppLogic.AppConfig("LiveServer");
                }
                cookie.Expires = DateTime.Now.AddYears(-30);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            catch { }
        }

        public static string MakeProperObjectName(string pname, string vname, string LocaleSetting)
        {
            vname = XmlCommon.GetLocaleEntry(vname, LocaleSetting, true);
            pname = XmlCommon.GetLocaleEntry(pname, LocaleSetting, true);
            if (vname.Trim().Length == 0 || pname == vname)
            {
                return pname.Trim();
            }
            else
            {
                return vname.Trim();
            }
        }

        public static string MakeProperProductName(string ProductID, string VariantID, string LocaleSetting)
        {
            return string.Empty;
        }

        public static string MakeProperProductSKU(string pSKU, string vSKU, string colorMod, string sizeMod)
        {
            return pSKU + vSKU + colorMod + sizeMod;
        }

        public static string Receipt(Customer ViewingCustomer)
        {
            string PackageName = AppLogic.AppConfig("XmlPackage.OrderReceipt");
            string result = RunXmlPackage(PackageName, null, ViewingCustomer, ViewingCustomer.SkinID, string.Empty, null, true, true);
            return result;
        }

        public static string Receipt(Customer ViewingCustomer, string orderNumber)
        {
            // Demand the order number so it could be used as the value for the parameter
            // of the stored procedure call within the xml package.
            string result = string.Empty;
            string PackageName = string.Empty;
            var parmList = new List<XmlPackageParam>();
            try
            {
                PackageName = AppLogic.AppConfig("XmlPackage.OrderReceipt");
                var parm = new XmlPackageParam();
                parm.Name = "ordernumber";
                parm.Value = orderNumber;
                parmList.Add(parm);
                result = RunXmlPackage(PackageName, null, ViewingCustomer, ViewingCustomer.SkinID, string.Empty, parmList, true, true);
            }
            catch
            {
                // if there is an exception then blank the result so that no email will be sent to the customer
                result = string.Empty;
            }
            return result;
        }

        public static void SendMail(string subject, string body, bool useHTML)
        {
            SendMail(subject, body, useHTML, AppLogic.AppConfig("MailMe_FromAddress"), AppLogic.AppConfig("MailMe_FromName"), AppLogic.AppConfig("MailMe_ToAddress"), AppLogic.AppConfig("MailMe_ToName"), string.Empty, AppLogic.AppConfig("MailMe_Server"));
        }

        public static void SendMail(string subject, string body, bool useHTML, string fromaddress, string fromname, string toaddress, string toname, string bccaddresses, string server)
        {
            if (false == server.Equals("TBD", StringComparison.InvariantCultureIgnoreCase) &&
                false == server.Equals("MAIL.YOURDOMAIN.COM", StringComparison.InvariantCultureIgnoreCase) &&
                server.Length != 0)
            { SendMail(subject, body, useHTML, fromaddress, fromname, toaddress, toname, bccaddresses, string.Empty, server, string.Empty, false, false, false); }
            else
            { SendMailRequest(subject, body, useHTML, fromaddress, fromname, toaddress, toname, bccaddresses, string.Empty, string.Empty, false, false, false); }
        }

        public static void SendMail(string subject, string body, bool useHTML, string fromaddress, string fromname, string toaddress, string toname, string bccaddresses, string server, bool throwError)
        {
            if (false == server.Equals("TBD", StringComparison.InvariantCultureIgnoreCase) &&
                false == server.Equals("MAIL.YOURDOMAIN.COM", StringComparison.InvariantCultureIgnoreCase) &&
                server.Length != 0)
            { SendMail(subject, body, useHTML, fromaddress, fromname, toaddress, toname, bccaddresses, string.Empty, server, string.Empty, false, false, throwError); }
            else
            { SendMailRequest(subject, body, useHTML, fromaddress, fromname, toaddress, toname, bccaddresses, string.Empty, string.Empty, false, false, throwError); }
        }

        public static void SendMail(string subject, string body, bool useHTML, string fromaddress, string fromname, string toaddress, string toname, string bccaddresses, string ReplyTo, string server, string orderNumber, bool createAttachment, bool multipleAttachment)
        {
            if (false == server.Equals("TBD", StringComparison.InvariantCultureIgnoreCase) &&
                false == server.Equals("MAIL.YOURDOMAIN.COM", StringComparison.InvariantCultureIgnoreCase) &&
                server.Length != 0)
            { SendMail(subject, body, useHTML, fromaddress, fromname, toaddress, toname, bccaddresses, ReplyTo, server, orderNumber, createAttachment, multipleAttachment, false); }
            else { SendMailRequest(subject, body, useHTML, fromaddress, fromname, toaddress, toname, bccaddresses, ReplyTo, orderNumber, createAttachment, multipleAttachment, false); }
        }

        // mask errors on store site, better to have a lost receipt than crash the site
        // on admin site, throw exceptions
        public static void SendMail(string subject, string body, bool useHTML, string fromaddress, string fromname, string toaddress, string toname, string bccaddresses, string ReplyTo, string server, string orderNumber, bool createAttachment, bool multipleAttachment, bool throwError)
        {
            if (false == server.Equals("TBD", StringComparison.InvariantCultureIgnoreCase) &&
                false == server.Equals("MAIL.YOURDOMAIN.COM", StringComparison.InvariantCultureIgnoreCase) &&
                server.Length != 0)
            {
                var msg = new System.Net.Mail.MailMessage(new MailAddress(fromaddress, fromname), new MailAddress(toaddress, toname));
                if (ReplyTo.Length != 0)
                {
                    msg.ReplyToList.Add(ReplyTo);
                }
                msg.Subject = subject;
                msg.Body = body;
                msg.IsBodyHtml = useHTML;
                if (bccaddresses.Length != 0)
                {
                    var mc = new MailAddressCollection();
                    foreach (string s in bccaddresses.Split(new char[] { ',', ';' }))
                    {
                        msg.Bcc.Add(new MailAddress(s));
                    }
                }

                // Create  the file attachment for this e-mail message.
                if (createAttachment)
                {
                    if (multipleAttachment)
                    {
                        foreach (string singleOrderNumber in orderNumber.Split(','))
                        {
                            Attachment reportAttachment = InterpriseHelper.ExportReportAsAttachment(singleOrderNumber);
                            msg.Attachments.Add(reportAttachment);
                        }
                    }
                    else
                    {
                        Attachment reportAttachment = InterpriseHelper.ExportReportAsAttachment(orderNumber);
                        msg.Attachments.Add(reportAttachment);
                    }
                }

                SmtpClient client = new SmtpClient(server);
                if (AppLogic.AppConfig("MailMe_User").Length != 0)
                {
                    System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(AppLogic.AppConfig("MailMe_User"), AppLogic.AppConfig("MailMe_Pwd"));
                    client.UseDefaultCredentials = false;
                    client.Credentials = SMTPUserInfo;
                }
                else
                {
                    client.Credentials = CredentialCache.DefaultNetworkCredentials;
                }
                //Added to support SSL and non-standard port configurations
                client.EnableSsl = AppLogic.AppConfigBool("MailMe_UseSSL");
                client.Port = AppLogic.AppConfigNativeInt("MailMe_Port");
                //End SSL Support
                try
                {
                    client.Send(msg);
                }
                catch (Exception ex)
                {
                    if (throwError)
                    {
                        throw new ArgumentException("Mail Error occurred - " + CommonLogic.GetExceptionDetail(ex, "<br />"));
                    }
                }
                finally
                {
                    msg.Dispose();
                }
            }
            else
            {
                SendMailRequest(subject, body, useHTML, fromaddress, fromname, toaddress, toname, bccaddresses, ReplyTo, orderNumber, createAttachment, multipleAttachment, throwError);
                //if (throwError)
                //{
                //    throw new ArgumentException("Invalid Mail Server: " + server);
                //}
            }
        }

        public static bool HasBadWords(string s)
        {
            s = s.ToUpper();

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, "select upper(Word) as BadWord from EcommerceBadWord with (NOLOCK) where LocaleSetting=" + DB.SQuote(Thread.CurrentThread.CurrentUICulture.Name)))
                {
                    while (rs.Read())
                    {
                        if (s.IndexOf(DB.RSField(rs, "BadWord")) != -1)
                        {
                            rs.Close();
                            return true;
                        }
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// //Returns true if the Customer has previously purchased this product.
        /// </summary>
        public static bool Owns(string ProductID, string CustomerID)
        {
            int nCount = 0;
            //VIP users have total access
            if (HttpContext.Current.User.IsInRole("VIP"))
            {
                return true;
            }

            if (ProductID.Length != 0)
            {
                nCount = DB.GetSqlN(string.Format("select count(cso.counter) as N from customersalesorder cso with (NOLOCK) inner join customersalesorderdetail csod with (NOLOCK) on csod.salesordercode = cso.salesordercode where billtocode = {0} and itemcode = {1}", DB.SQuote(CustomerID), DB.SQuote(ProductID)));

                if (nCount != 0)
                {
                    return true;
                }
            }
            return false;
        }

        // gets roles of current httpcontext user, prior set by SetRoles
        public static string GetRoles()
        {
            string tmpS = string.Empty;
            try
            {
                var p = (InterpriseSuiteEcommercePrincipal)HttpContext.Current.User;
                tmpS = p.Roles;
            }
            catch { }
            return tmpS;
        }

        /// <summary>
        /// Sets the Roles of the logged in user and adds them to their security Principal
        /// This must be called in Application_AuthenticateRequest of Global.asax
        /// </summary>
        public static void SetRoles()
        {
            if (!HttpContext.Current.Request.IsAuthenticated) { return; }

            var roleList = new ArrayList(50); //List of Role Strings
            string CustomerGUID = HttpContext.Current.User.Identity.Name;
            string CustomerID = string.Empty;
            string CustomerLevelID = string.Empty;
            DateTime SubscriptionExpiresOn = DateTime.Now;

            //Everybody that is not anonymous Gets "Free"
            roleList.Add("Free");

            if (CustomerGUID.Length == 0) { return; }

            // Admins and super users rule!
            if (Customer.StaticIsAdminUser(CustomerID))
            {
                roleList.Add("Admin");
            }
            if (Customer.StaticIsAdminSuperUser(CustomerID))
            {
                roleList.Add("SuperAdmin");
            }
            //Check Subscriber Expiration
            if (SubscriptionExpiresOn.CompareTo(DateTime.Now) > 0)
            {
                roleList.Add("Subscriber");
            }

            string[] roles = (string[])roleList.ToArray(typeof(string));
        }

        public static string GetMicroPayProductID()
        {
            string tmp = string.Empty;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var rs = DB.GetRSFormat(con, "select ItemCode as ProductID from InventoryItem  with (NOLOCK) where Status='A'"))
                {
                    if (rs.Read())
                    {
                        tmp = DB.RSField(rs, "ProductID");
                    }
                }
            }
            return tmp;
        }

        public static string GetAdHocProductID()
        {
            string tmp = string.Empty;

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, "select ItemCode as ProductID from InventoryItem  with (NOLOCK) where Status='A'"))
                {
                    if (rs.Read())
                    {
                        tmp = DB.RSField(rs, "ProductID");
                    }
                }
            }

            return tmp;
        }

        public static decimal GetMicroPayBalance(string CustomerID)
        {
            decimal result = System.Decimal.Zero;
            if (CustomerID.Length != 0)
            {

                using (SqlConnection con = DB.NewSqlConnection())
                {
                    con.Open();
                    using (IDataReader rs = DB.GetRSFormat(con, String.Format("select MicroPayBalance from Customer  with (NOLOCK) where CustomerID={0}", CustomerID)))
                    {
                        if (rs.Read())
                        {
                            result = DB.RSFieldDecimal(rs, "MicroPayBalance");
                        }
                    }
                }
            }
            return result;
        }

        public static string GetString(string key, int SkinID, string LocaleSetting, bool retunTextOnly = false)
        {
            if (AppLogic.AppConfigBool("ShowStringResourceKeys"))
            {
                return key;
            }
            if (StringResourceTable == null || StringResourceTable.Count == 0)
            {
                LoadStringResourcesFromDB(true);
            }

            if (StringResourceTable == null || StringResourceTable.Count == 0)
            {
                if (AppLogic.MailServer().Length != 0 &&
                    false == AppLogic.ro_TBD.Equals(AppLogic.MailServer(), StringComparison.InvariantCultureIgnoreCase))
                {
                    try
                    {
                        string Explanation = "This message means that your site is flushing application memory for some (unknown) reason. If you get this e-mail more then very rarely, it could be a big performance impact, and you should check with your hosting provider about this issue. Their server may be running low of RAM or something is causing their application asp.net memory caches to get flushed. This could cause your site to send up to 1000 database queries to the store on every single page load. If our store sends you an e-mail (which is VERY rare), it's not for a minor issue. First, please check with your hosting provider.";
                        AppLogic.SendMail(AppLogic.AppConfig("StoreName") + " string Table Empty Incident", "string Tables Empty, Reloaded at " + Localization.ToNativeDateTimeString(System.DateTime.Now) + ".<br/><br/>" + Explanation, false, AppLogic.AppConfig("MailMe_FromAddress"), AppLogic.AppConfig("MailMe_FromName"), AppLogic.AppConfig("MailMe_ToAddress"), AppLogic.AppConfig("MailMe_ToName"), string.Empty, AppLogic.MailServer());
                    }
                    catch { }
                }
                return key; // they don't even have this locale, return the key as a placeholder
            }

            var sr = StringResourceTable[LocaleSetting, key];
            if (sr == null)
            {
                return key;
            }
            else
            {
                //Handles to some pages when Customer has not been initialized
                if (Customer.Current != null)
                {
                    bool isEditingMode = Customer.Current.IsInEditingMode();
                    bool isAdminLoggedIn = Security.IsAdminCurrentlyLoggedIn();
                    bool isInMobileMode = CurrentContext.IsRequestingFromMobileMode(Customer.Current);

                    //when admin is not loggedin and user not in editing
                    if (retunTextOnly || (!isEditingMode && !isAdminLoggedIn))
                    {
                        return sr.ConfigValue;
                    }
                    //when admin is loggedin and user not in editing
                    else if (!isEditingMode && isAdminLoggedIn)
                    {
                        return sr.ConfigValue;
                    }
                    //when admin is not loggedin but user in editing
                    else if (isEditingMode && !isAdminLoggedIn)
                    {
                        return sr.ConfigValue;
                    }
                    else if (isInMobileMode)
                    {
                        return sr.ConfigValue;
                    }

                    return BuildCmsTemplate(key, sr.ConfigValue);
                }
                else
                {
                    return sr.ConfigValue;
                }
            }
        }

        private static string BuildCmsTemplate(string key, string value)
        {
            string html = String.Empty;
            var cachingInstance = CachingFactory.RequestCachingEngineInstance;

            if (!cachingInstance.Exist(DomainConstants.CMS_TEMPLATE))
            {
                var xml = new XElement(DomainConstants.XML_ROOT_NAME);
                xml.Add(new XElement(DomainConstants.XML_SECTION_TYPE, XMLSectionType.DISPLAY_CMS_TEMPLATE));
                
                var XmlPackage = new XmlPackage2("helper.page.default.xml.config", xml);

                html = XmlPackage.TransformString();
                cachingInstance.AddItem(DomainConstants.CMS_TEMPLATE, html);
            }
            else 
            {
                html = cachingInstance.GetItem<string>(DomainConstants.CMS_TEMPLATE);
            }

            string elementHtmlText = value;
            bool hasContentTag = value.Contains('{') || value.Contains('"') || value.Contains('\'') ;
            if(hasContentTag) value = String.Empty;

            return html.Replace("(0)", key).Replace("(1)", value).Replace("(2)", hasContentTag.ToString()).Replace("(3)", elementHtmlText);

        }

        // ----------------------------------------------------------------
        //
        // STRING RESOURCE SUPPORT ROUTINES
        //
        // ----------------------------------------------------------------
        public static void SetStringResource(int StringResourceID, string Name, string UseText, string LocaleSetting)
        {
            Name = Name.Trim();
            if (StringResourceTable[LocaleSetting, Name] == null)
            {
                StringResource newStringResource = StringResource.New(LocaleSetting, Name, UseText);
                newStringResource.Save();

                StringResourceTable.Add(newStringResource);
            }
            else
            {
                StringResourceTable[LocaleSetting, Name].ConfigValue = UseText;
            }
        }

        // ----------------------------------------------------------------
        //
        // APPCONFIG SUPPORT ROUTINES
        //
        // ----------------------------------------------------------------
        public static void SetAppConfig(int AppConfigID, string Name, string ConfigValue)
        {
            Name = Name.Trim();
            if (AppConfigTable[Name] == null)
            {
                AppConfigTable.Add(InterpriseSuiteEcommerceCommon.AppConfig.Create(AppConfigID, Name, "", ConfigValue, "Custom", false));
            }
            else
            {
                AppConfigTable[Name].ConfigValue = ConfigValue;
            }
        }

        public static bool AppConfigExists(string paramName)
        {
            return (AppConfigTable[paramName] != null);
        }

        public static string AppConfig(string paramName)
        {
            if (AppConfigTable[paramName] != null)
            {
                return AppConfigTable[paramName].ConfigValue;
            }
            return string.Empty;
        }

        public static bool AppConfigBool(string paramName)
        {
            string tmp = AppConfig(paramName);
            return ("TRUE".Equals(tmp, StringComparison.InvariantCultureIgnoreCase) ||
                "YES".Equals(tmp, StringComparison.InvariantCultureIgnoreCase) ||
                "1".Equals(tmp, StringComparison.InvariantCultureIgnoreCase));
        }

        public static int AppConfigUSInt(string paramName)
        {
            return Localization.ParseUSInt(AppConfig(paramName));
        }

        public static long AppConfigUSLong(string paramName)
        {
            string tmpS = AppConfig(paramName);
            return Localization.ParseUSLong(tmpS);
        }

        public static Single AppConfigUSSingle(string paramName)
        {
            return Localization.ParseUSSingle(AppConfig(paramName));
        }

        public static Double AppConfigUSDouble(string paramName)
        {
            return Localization.ParseUSDouble(AppConfig(paramName));
        }

        public static Decimal AppConfigUSDecimal(string paramName)
        {
            return Localization.ParseUSDecimal(AppConfig(paramName));
        }

        public static DateTime AppConfigUSDateTime(string paramName)
        {
            return Localization.ParseUSDateTime(AppConfig(paramName));
        }

        public static int AppConfigNativeInt(string paramName)
        {
            return Localization.ParseNativeInt(AppConfig(paramName));
        }

        public static long AppConfigNativeLong(string paramName)
        {
            return Localization.ParseNativeLong(AppConfig(paramName));
        }

        public static Single AppConfigNativeSingle(string paramName)
        {
            return Localization.ParseNativeSingle(AppConfig(paramName));
        }

        public static Double AppConfigNativeDouble(string paramName)
        {
            return Localization.ParseNativeDouble(AppConfig(paramName));
        }

        public static Decimal AppConfigNativeDecimal(string paramName)
        {
            return Localization.ParseNativeDecimal(AppConfig(paramName));
        }

        public static DateTime AppConfigNativeDateTime(string paramName)
        {
            return Localization.ParseNativeDateTime(AppConfig(paramName));
        }

        public static void GetButtonDisable(WebControl btn)
        {
            var sbValid = new StringBuilder(1024);
            sbValid.Append("if (typeof(Page_ClientValidate) == 'function') { ");
            sbValid.Append("if (Page_ClientValidate() == false) { return false; }} ");
            sbValid.Append("this.disabled = true;");
            sbValid.Append("document.getElementById(\"" + btn.ClientID + "\").disabled = true;");
            //GetPostBackEventReference obtains a reference to a client-side script function that causes the server to post back to the page.
            sbValid.Append(btn.Page.ClientScript.GetPostBackEventReference(btn, string.Empty));
            sbValid.Append(";");
            btn.Attributes.Add("onclick", sbValid.ToString());
        }

        /// <summary>
        /// Gets the preferred skin Id
        /// </summary>
        /// <returns></returns>
        public static int GetCurrentSkinID()
        {
            int skinId = 1;
            // first try the query string
            skinId = CommonLogic.QueryStringUSInt("SkinID");

            // next the cookie
            if (skinId == 0)
            {
                skinId = CommonLogic.CookieUSInt(ro_SkinCookieName);
            }
            // if not present, retrieve from appconfig
            if (skinId == 0)
            {
                skinId = AppLogic.AppConfigUSInt("DefaultSkinID");
            }
            if (skinId == 0)
            {
                skinId = 1;
            }

            return skinId;
        }

        public static string RequestInputStreamToString()
        {
            StringBuilder sb = new StringBuilder();
            int streamLength;
            int streamRead;
            Stream s = HttpContext.Current.Request.InputStream;
            streamLength = Convert.ToInt32(s.Length);

            Byte[] streamArray = new Byte[streamLength];

            streamRead = s.Read(streamArray, 0, streamLength);

            for (int i = 0; i < streamLength; i++)
            {
                sb.Append(Convert.ToChar(streamArray[i]));
            }

            return sb.ToString();
        }

        public static string LocateImageUrl(string entity, int id, string size)
        {
            return LocateImageUrl(entity, id, size, -1, AppLogic.AppConfigBool("Watermark.Enabled"));
        }

        public static string LocateImageUrl(string entity, int id, string size, int index, bool watermark)
        {
            bool existing;
            return LocateImageUrl(entity, id, size, index, watermark, out existing);
        }

        public static string LocateImageUrl(string entity, int id, string size, int index, bool watermark, out bool existing)
        {
            existing = false;
            entity = entity.ToLowerInvariant();
            size = size.ToLowerInvariant();

            string root = string.Empty;
            bool useRemoteImages = false;

            useRemoteImages = AppLogic.AppConfigBool("RemoteImages.Enabled");

            if (useRemoteImages)
            {
                root = AppLogic.AppConfig("RemoteImages.Url");
            }

            string url = string.Empty;

            if (useRemoteImages)
            {
                url = string.Format(
                    "{0}/lookupimage.aspx?entity={1}&id={2}&size={3}&index={4}",
                    root,
                    HttpUtility.UrlEncode(entity),
                    HttpUtility.UrlEncode(id.ToString()),
                    HttpUtility.UrlEncode(size),
                    HttpUtility.UrlEncode(index.ToString())
                );
            }
            else
            {
                string[] _supportedExtensions = new string[] { "jpg", "gif", "png" };

                //Start ImageFileNameOverride code ---------------->
                bool hasImageOverride = false;
                string imageOverrideFileName = string.Empty;
                if (hasImageOverride)
                {
                    string imageOverrideColumn = string.Format("ImageOverride{0}{1}_C", size, CommonLogic.IIF(index > 0, index.ToString(), string.Empty));
                    using (var con = DB.NewSqlConnection())
                    {
                        con.Open();
                        using (var ds = DB.GetDS(string.Concat("SELECT * FROM InventoryItem with (NOLOCK) WHERE Counter = ", id), false))
                        {
                            foreach (DataColumn col in ds.Tables[0].Columns)
                            {
                                if (col.ColumnName.ToLower() != imageOverrideColumn.ToLower()) { continue; }
                                if (ds.Tables[0].Rows.Count == 0) { continue; }

                                imageOverrideFileName = ds.Tables[0].Rows[0][imageOverrideColumn].ToString();
                                if (!string.IsNullOrEmpty(imageOverrideFileName))
                                {
                                    hasImageOverride = true;
                                }
                                break;

                            }
                        }
                    }

                    for (int i = 0; i < _supportedExtensions.Length; i++)
                    {

                        if (CurrentContext.IsRequestingFromMobileMode(Customer.Current))
                        {
                            if (size != "swatch") { size = "mobile"; }
                        }

                        url = string.Format("{0}images/{1}/{2}/{3}", root, entity, size, imageOverrideFileName + "." + _supportedExtensions[i]);
                        existing = CommonLogic.FileExists(url);
                        if (!existing) continue;

                        if (watermark)
                        {
                            url = "watermark.axd?e=0&size=" + size + "&src=" + HttpUtility.UrlEncode(url);
                        }
                        break;
                    }
                }
                //<-------------ImageFileNameOverride code.
                //reuse code below for entity images display
                else
                {
                    foreach (string extension in _supportedExtensions)
                    {
                        if (CurrentContext.IsRequestingFromMobileMode(Customer.Current))
                        {
                            if (size != "swatch") { size = "mobile"; }
                        }

                        url = string.Format("{0}images/{1}/{2}/{3}.{4}", root, entity, size, CommonLogic.IIF(index > 0, string.Format("{0}_{1}", id, index), id.ToString()), extension);
                        existing = CommonLogic.FileExists(url);
                        if (!existing) { continue; }

                        if (watermark)
                        {
                            url = "watermark.axd?e=0&size=" + size + "&src=" + HttpUtility.UrlEncode(url);
                        }
                        break;
                    }
                }

                if (!existing)
                {
                    bool useIcon = size.Equals("icon", StringComparison.InvariantCultureIgnoreCase) ||
                                    size.Equals("micro", StringComparison.InvariantCultureIgnoreCase) ||
                                    size.Equals("minicart", StringComparison.InvariantCultureIgnoreCase) ||
                                    size.Equals("swatch", StringComparison.InvariantCultureIgnoreCase);
                    if (entity.Equals("product", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (size.Equals("minicart", StringComparison.InvariantCultureIgnoreCase))
                        {
                            url = string.Format("skins/skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "images/nopictureminicart.gif", "images/nopicture.gif"));
                        }
                        else
                        {
                            url = string.Format("skins/skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "images/nopictureicon.gif", "images/nopicture.gif"));
                        }
                    }
                    else
                    {
                        if (size.Equals("minicart", StringComparison.InvariantCultureIgnoreCase))
                        {
                            url = string.Format("skins/Skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "images/nopictureminicart_entity.gif", "images/nopicture_entity.gif"));
                        }
                        else
                        {
                            url = string.Format("skins/Skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "images/nopictureicon_entity.gif", "images/nopicture_entity.gif"));
                        }
                    }
                }
            }
            return url;
        }

        /// <summary>
        /// This will return URL using image filename
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="itemcode"></param>
        /// <param name="size"></param>
        /// <param name="filename"></param>
        /// <param name="watermark"></param>
        /// <param name="existing"></param>
        /// <returns></returns>
        public static string LocateImageFilenameUrl(string entity, string itemcode, string size, string filename, bool watermark, out bool existing)
        {
            existing = false;
            entity = entity.ToLowerInvariant();
            size = size.ToLowerInvariant();

            string root = string.Empty;
            bool useRemoteImages = false;

            useRemoteImages = AppLogic.AppConfigBool("RemoteImages.Enabled");

            if (useRemoteImages)
            {
                root = AppLogic.AppConfig("RemoteImages.Url");
            }

            string url = string.Empty;

            if (useRemoteImages)
            {
                url = string.Format(
                    "{0}/lookupimage.aspx?entity={1}&itemcode={2}&size={3}&filename={4}",
                    root,
                    HttpUtility.UrlEncode(entity),
                    HttpUtility.UrlEncode(itemcode),
                    HttpUtility.UrlEncode(size),
                    HttpUtility.UrlEncode(filename)
                );
            }
            else if (AppLogic.AppConfigBool("ImageFileNameOverride.Enabled"))
            {
                string[] _supportedExtensions = new string[] { "jpg", "gif", "png" };

                //Start ImageFileNameOverride code ---------------->
                bool hasImageOverride = true;
                string imageOverrideFileName = string.Empty;
                if (hasImageOverride)
                {
                    string imageOverrideColumn = string.Format("ImageOverride{0}_C", size);

                    using (SqlConnection con = DB.NewSqlConnection())
                    {
                        con.Open();

                        using (DataSet ds = DB.GetDS(string.Format("SELECT * FROM InventoryItem with (NOLOCK) WHERE ItemCode = '{0}'", itemcode), false))
                        {
                            if (ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Columns.Contains(imageOverrideColumn))
                            {
                                imageOverrideFileName = ds.Tables[0].Rows[0][imageOverrideColumn].ToString();
                                if (!string.IsNullOrEmpty(imageOverrideFileName))
                                    hasImageOverride = true;
                            }
                        }
                    }

                    for (int i = 0; i < _supportedExtensions.Length; i++)
                    {

                        if (CurrentContext.IsRequestingFromMobileMode(Customer.Current))
                        {
                            if (size != "swatch") { size = "mobile"; }
                        }

                        url = string.Format(
                                "{0}images/{1}/{2}/{3}",
                                root,
                                entity,
                                size,
                                imageOverrideFileName + "." + _supportedExtensions[i]);

                        existing = CommonLogic.FileExists(url);
                        if (existing)
                        {
                            if (watermark)
                            {
                                url = "watermark.axd?e=0&size=" + size + "&src=" + HttpUtility.UrlEncode(url);
                            }
                            break;
                        }
                    }
                }
                //<-------------ImageFileNameOverride code.           
                if (!existing)
                {
                    bool useIcon = size.Equals("icon", StringComparison.InvariantCultureIgnoreCase) ||
                                size.Equals("micro", StringComparison.InvariantCultureIgnoreCase) ||
                                size.Equals("minicart", StringComparison.InvariantCultureIgnoreCase) ||
                                size.Equals("swatch", StringComparison.InvariantCultureIgnoreCase);

                    if (entity.Equals("product", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (size.Equals("minicart", StringComparison.InvariantCultureIgnoreCase))
                        {
                            url = string.Format("skins/skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "/images/nopictureminicart.gif", "images/nopicture.gif"));
                        }
                        else
                        {
                            url = string.Format("skins/skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "/images/nopictureicon.gif", "images/nopicture.gif"));
                        }
                    }
                    else
                    {
                        if (size.Equals("minicart", StringComparison.InvariantCultureIgnoreCase))
                        {
                            url = string.Format("skins/Skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "images/nopictureminicart_entity.gif", "images/nopicture_entity.gif"));
                        }
                        else
                        {
                            url = string.Format("skins/Skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "images/nopictureicon_entity.gif", "images/nopicture_entity.gif"));
                        }
                    }
                }
            }
            else
            {
                return LocateImageFileOverride(entity, size, filename, watermark, out existing);
            }

            return url;

        }

        private static string LocateImageFileOverride(string entity, string size, string filename, bool watermark, out bool existing)
        {
            string[] _supportedExtensions = new string[] { "jpg", "gif", "png" };
            string imageFileName = string.Empty;
            string url = string.Empty;
            string root = string.Empty;
            existing = false;

            if (filename.Length > 0)
            {
                imageFileName = filename;
                for (int i = 0; i < _supportedExtensions.Length; i++)
                {
                    if (CurrentContext.IsRequestingFromMobileMode(Customer.Current))
                    {
                        if (size != "swatch") { size = "mobile"; }
                    }

                    url = string.Format("{0}images/{1}/{2}/{3}", root, entity, size, imageFileName.Split('.')[0] + "." + _supportedExtensions[i]);

                    existing = CommonLogic.FileExists(url);

                    if (!existing) continue;

                    if (watermark)
                    {
                        url = "watermark.axd?e=0&size=" + size + "&src=" + HttpUtility.UrlEncode(url);
                    }

                    break;
                }
            }

            if (!existing)
            {
                bool useIcon = size.Equals("icon", StringComparison.InvariantCultureIgnoreCase) ||
                                size.Equals("micro", StringComparison.InvariantCultureIgnoreCase) ||
                                size.Equals("minicart", StringComparison.InvariantCultureIgnoreCase) ||
                                size.Equals("swatch", StringComparison.InvariantCultureIgnoreCase);

                if (entity.Equals("product", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (size.Equals("minicart", StringComparison.InvariantCultureIgnoreCase))
                    {
                        url = string.Format("skins/skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "/images/nopictureminicart.gif", "images/nopicture.gif"));
                    }
                    else
                    {
                        url = string.Format("skins/skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "/images/nopictureicon.gif", "images/nopicture.gif"));
                    }
                }
                else
                {
                    if (size.Equals("minicart", StringComparison.InvariantCultureIgnoreCase))
                    {
                        url = string.Format("skins/skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "images/nopictureminicart_entity.gif", "images/nopicture_entity.gif"));
                    }
                    else
                    {
                        url = string.Format("skins/skin_{0}/{1}", AppLogic.GetCurrentSkinID(), CommonLogic.IIF(useIcon, "images/nopictureicon_entity.gif", "images/nopicture_entity.gif"));
                    }
                }
            }
            return url;
        }

        public static void ClearCCInDB()
        {
            DB.ExecuteSQL("RemoveCreditCardReferences");
        }

        public static void ClearSession()
        {
            DB.ExecuteSQL("DELETE EcommerceCustomerSession");
        }

        public static string GetVATSelectList(Customer ThisCustomer)
        {
            if (!AppConfigBool("VAT.Enabled"))
            {
                return string.Empty;
            }

            string SelectName = "VATSelectList";
            string OnChangeHandler = "self.location='setvatsetting.aspx?returnURL=" + Security.UrlEncode(HttpContext.Current.Request.Url.PathAndQuery) + "&vatsetting=' + document.getElementById('VATSelectList').value";
            string CssClass = string.Empty;
            var tmpS = new StringBuilder(4096);
            tmpS.Append("<select size=\"1\" id=\"" + SelectName + "\" name=\"" + SelectName + "\"");
            if (OnChangeHandler.Length != 0)
            {
                tmpS.Append(" onChange=\"" + OnChangeHandler + "\"");
            }
            if (CssClass.Length != 0)
            {
                tmpS.Append(" class=\"" + CssClass + "\"");
            }
            tmpS.Append(">");

            string msg1 = AppLogic.GetString("setvatsetting.aspx.4", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            string msg2 = AppLogic.GetString("setvatsetting.aspx.2", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
            string msg3 = AppLogic.GetString("setvatsetting.aspx.3", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);

            tmpS.Append("<option value=\"" + ((int)VatDefaultSetting.Inclusive).ToString() + "\" " + CommonLogic.IIF(ThisCustomer.VATSettingRaw == VatDefaultSetting.Inclusive, " selected ", "") + ">" + msg2 + "</option>");
            tmpS.Append("<option value=\"" + ((int)VatDefaultSetting.Exclusive).ToString() + "\" " + CommonLogic.IIF(ThisCustomer.VATSettingRaw == VatDefaultSetting.Exclusive, " selected ", "") + ">" + msg3 + "</option>");

            tmpS.Append("</select>");
            return tmpS.ToString();
        }

        public static string GetStoreVersion()
        {
            string tmp = string.Empty;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, "SELECT TOP 1 * FROM eCommerceVersion with (NOLOCK) "))
                {
                    if (reader.Read())
                    {
                        tmp = DB.RSField(reader, "Version");
                    }
                }
            }
            return tmp;
        }

        public static string GetItemCode(string itemCode)
        {
            string actualItemCode = string.Empty;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, string.Format("SELECT CASE WHEN IsPriceListSalesPriceByTotalQty = 1 THEN ItemCode ELSE '{0}' END AS ItemCode FROM InventoryMatrixGroup WHERE ItemCode = (SELECT ItemCode FROM InventoryMatrixItem WHERE MatrixItemCode = '{0}')", itemCode)))
                {
                    if (reader.Read())
                    {
                        actualItemCode = DB.RSField(reader, "ItemCode");
                    }
                }
            }
            return actualItemCode;
        }

        public static void GetSEImageAttributes(string itemCode, string imgSize, string langCode, ref string seTitle, ref string seAltText)
        {
            string website = DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode);
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, string.Format("SELECT TOP 1 * FROM InventoryImageWebOptionDescription with (NOLOCK) WHERE ItemCode = '{0}' AND WebSiteCode = {1} AND LanguageCode = '{2}'", itemCode, website, langCode)))
                {
                    if (reader.Read())
                    {
                        switch (imgSize.ToUpperInvariant())
                        {
                            case "ICON":
                                seTitle = DB.RSField(reader, "SETitleIcon");
                                seAltText = DB.RSField(reader, "SEAltTextIcon");
                                break;
                            case "MEDIUM":
                                seTitle = DB.RSField(reader, "SETitleMedium");
                                seAltText = DB.RSField(reader, "SEAltTextMedium");
                                break;
                            case "MINICART":
                                seTitle = DB.RSField(reader, "SETitleMedium");
                                seAltText = DB.RSField(reader, "SEAltTextMedium");
                                break;
                            case "LARGE":
                                seTitle = DB.RSField(reader, "SETitleLarge");
                                seAltText = DB.RSField(reader, "SEAltTextLarge");
                                break;
                        }
                        seTitle.Replace("'", "''");
                        seAltText.Replace("'", "''");
                    }
                }
            }
        }

        public static ItemAttributesContainer GetSEImageAttributesByObject(string itemCode, string langCode)
        {
            string website = DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode);
            var containerAttribute = new ItemAttributesContainer();
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, string.Format("SELECT TOP 1 * FROM InventoryImageWebOptionDescription with (NOLOCK) WHERE ItemCode = '{0}' AND WebSiteCode = {1} AND LanguageCode = '{2}'", itemCode, website, langCode)))
                {
                    if (reader.Read())
                    {
                        containerAttribute.IconAlt = DB.RSField(reader, "SEAltTextIcon").Replace("'", "''");
                        containerAttribute.IconTitle = DB.RSField(reader, "SETitleIcon").Replace("'", "''");

                        containerAttribute.MediumTitle = DB.RSField(reader, "SETitleMedium").Replace("'", "''");
                        containerAttribute.MediumAlt = DB.RSField(reader, "SEAltTextMedium").Replace("'", "''");

                        containerAttribute.LargeAlt = DB.RSField(reader, "SEAltTextLarge").Replace("'", "''");
                        containerAttribute.LargeTitle = DB.RSField(reader, "SETitleLarge").Replace("'", "''");
                    }
                }
            }

            return containerAttribute;
        }

        //use this method to initialize cached settings
        public static void InitializeCachedSettings()
        {
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader reader = DB.GetRSFormat(con, "SELECT IsAllowFractional,QuantityDecimalPlace FROM InventoryPreference WITH(NOLOCK)"))
                {
                    if (reader.Read())
                    {
                        IsAllowFractional = DB.RSFieldBool(reader, "IsAllowFractional");
                        InventoryDecimalPlacesPreference = DB.RSFieldInt(reader, "QuantityDecimalPlace");
                    }
                }
            }
        }

        public static string AllowedQuantityWithDecimalRegEx(string LocalSetting)
        {
            string reEx = "^\\d{0,2}(GROUP_SEPARATOR?\\d{NUMBER_GROUP_SIZE})*(DECIMAL_SEPARATOR\\d{0,INVENTORY_DECIMAL_PLACES})?$".Replace("GROUP_SEPARATOR", Localization.GetNumberGroupSeparatorLocaleString(LocalSetting)).Replace("NUMBER_GROUP_SIZE", Localization.GetNumberGroupSizes(LocalSetting).ToString()).Replace("DECIMAL_SEPARATOR", Localization.GetNumberDecimalSeparatorLocaleString(LocalSetting)).Replace("INVENTORY_DECIMAL_PLACES", InventoryDecimalPlacesPreference.ToString());
            return reEx.Replace(".", "\\.").Replace(" ", "\\s");
        }

        public static string AllowedQuantityWithNoDecimalRegEx(string LocalSetting)
        {
            return @"^(\d+(,\d+)*)?$";
        }

        public static CurrentEntity GetCurrentEntity(System.Collections.Generic.Dictionary<string, EntityHelper> EntityHelpers)
        {
            foreach (string EntityName in ro_SupportedEntities)
            {
                string currentEntityID = string.Empty;
                string currentEntityType = string.Empty;
                if (CommonLogic.GetThisPageName(false).ToLowerInvariant() != "showproduct.aspx")
                {
                    currentEntityType = EntityName.ToUpperInvariant();
                    EntityHelper Helper = AppLogic.LookupHelper(EntityHelpers, EntityName);
                    currentEntityID = Helper.GetEntityName(Helper.GetCurrentEntityID(), Customer.Current.LocaleSetting);
                }
                else
                {
                    currentEntityType = "Product";
                    int itemCounter = CommonLogic.QueryStringUSInt("ProductID");
                    currentEntityID = InterpriseHelper.GetInventoryItemCode(itemCounter);

                }
                if (currentEntityID != string.Empty)
                {
                    CurrentEntity currentEntity = new CurrentEntity(false);
                    currentEntity.EntityID = currentEntityID;
                    currentEntity.EntityType = currentEntityType;
                    return currentEntity;
                }

            }
            return new CurrentEntity(true);
        }

        public static List<SystemPostalCode> GetSystemPostalCode(string countryname, string postalcode)
        {
            int top = 10;
            var lstPostalCode = new List<SystemPostalCode>();
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, "select top {2} PostalCode from systemPostalcode  with (NOLOCK) group by PostalCode, CountryCode having lower(CountryCode) = lower({0}) and PostalCode like '%{1}%'", CommonLogic.SQuote(countryname.ToLower()), postalcode, top.ToString()))
                {
                    while (reader.Read())
                    {
                        lstPostalCode.Add(new SystemPostalCode { PostalCode = reader["PostalCode"].ToString() });
                    }
                    reader.Close();
                }
            }
            return lstPostalCode;
        }

        public static List<KeyValuePair<string, string>> GetAvailableUnitMesure(string customerCode, string cartItemCode, bool showInventoryForAllWareHouse, bool customerIsNotRegistered)
        {
            var availableUnitMeasures = new List<KeyValuePair<string, string>>();
            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader reader = DB.GetRSFormat(con, "exec eCommerceGetProductUnitMeasureAvailability @CustomerCode = {0}, @ItemCode = {1}, @IncludeAllWarehouses = {2}, @Anon = {3}",
                                                                DB.SQuote(customerCode), DB.SQuote(cartItemCode), showInventoryForAllWareHouse, customerIsNotRegistered))
                {
                    while (reader.Read())
                    {
                        availableUnitMeasures.Add(new KeyValuePair<string, string>(DB.RSField(reader, "UnitMeasureCode"), DB.RSField(reader, "UnitMeasureDescription")));
                    }
                }
            }
            return availableUnitMeasures;
        }

        public static string GetUnitMeassureDescription(string unitMeasureCode)
        {
            string unitMeassure = string.Empty;
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, "SELECT UnitMeasureDescription FROM SystemUnitMeasure with (NOLOCK) WHERE UnitMeasureCode = {0}", DB.SQuote(unitMeasureCode)))
                {
                    if (reader.Read())
                    {
                        unitMeassure = DB.RSField(reader, "UnitMeasureDescription");
                    }
                    else
                    {
                        unitMeassure = unitMeasureCode;
                    }
                    reader.Close();
                }
                con.Close();
            }
            return unitMeassure;
        }

        public static List<MatrixAttributeValue> GetMatrixItemAttributes(string itemCode, string languageCode)
        {
            var list = new List<MatrixAttributeValue>();
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, string.Format("exec eCommerceGetMatrixItemAttributes @ItemCode = NULL, @MatrixItemCode = {0}, @WebsiteCode = {1}, @CurrentDate = {2}, @LanguageCode = {3}, @ContactCode = {4}",
                    DB.SQuote(itemCode), DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode), DB.SQuote(Localization.DateTimeStringForDB(DateTime.Now)), DB.SQuote(languageCode), DB.SQuote(Customer.Current.ContactCode))))
                {
                    if (reader.Read())
                    {
                        for (int ctr = 1; ctr <= 6; ctr++)
                        {
                            string attribute = DB.RSField(reader, string.Format("Attribute{0}", ctr));
                            string attributeValue = DB.RSField(reader, string.Format("Attribute{0}ValueDescription", ctr));

                            if (string.IsNullOrEmpty(attribute) && string.IsNullOrEmpty(attributeValue)) continue;

                            list.Add(new MatrixAttributeValue(attribute, attributeValue));
                        }
                    }
                }
            }
            return list;
        }

        public static IEnumerable<KitDetailItem> GetKitDetail(string itemCode, string currency, string localeSetting, string customerCode, Guid cartItemId, string contactcode)
        {
            var lstKitDetailItems = new List<KitDetailItem>();
            string kitDetailQuery =
                     string.Format(
                         "exec EcommerceGetWebKitCartDetail @ItemKitCode = {0}, @CurrencyCode = {1}, @LanguageCode = {2}, @CustomerCode = {3}, @CartID = {4}, @ContactCode = {5}",
                         DB.SQuote(itemCode),
                         DB.SQuote(currency), //cart.ThisCustomer.CurrencySetting,
                         DB.SQuote(localeSetting),
                         DB.SQuote(customerCode),
                         DB.SQuote(cartItemId.ToString()),
                         DB.SQuote(contactcode)
                     );

            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, kitDetailQuery))
                {
                    while (reader.Read())
                    {
                        lstKitDetailItems.Add(new KitDetailItem()
                        {
                            Name = DB.RSField(reader, "ItemDescription"),
                            Quantity = Convert.ToDecimal(DB.RSFieldDecimal(reader, "Quantity"))
                        });
                    }
                }
            }

            return lstKitDetailItems;
        }

        #region CheckNotification
        /// <summary>
        /// Check if customer is subscribe to notify on back stock or item price drop.
        /// </summary>
        /// <param name="customerCode">Customer Code</param>
        /// <param name="email">Customer Email</param>
        /// <param name="itemCode">Item Code</param>
        /// <param name="notificationType">Type of Notification</param>
        /// <returns>true/false</returns>
        public static bool CheckNotification(string contactCode, string email, string itemCode, int notificationType)
        {
            bool IsSubscribe = false;

            string query = string.Empty;
            query = string.Format("exec READECOMMERCENOTIFICATION {0}, {1}, {2}, {3}",
                    DB.SQuote(contactCode),
                    DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                    DB.SQuote(itemCode),
                    DB.SQuote(email));

            DataSet ds = null;
            ds = Interprise.Facade.Base.SimpleFacade.Instance.LoadDataSet(CommandType.Text, query, new string[] { "ECOMMERCENOTIFICATION" }, null);

            if (ds.Tables[0].Rows.Count > 0)
            {
                if (notificationType == 1)
                {
                    if (ds.Tables[0].Rows[0]["NotifyOnPriceDrop"].ToString() == "True")
                        IsSubscribe = true;
                }
                else
                {
                    if (ds.Tables[0].Rows[0]["NotifyOnItemAvail"].ToString() == "True")
                        IsSubscribe = true;
                }
            }
            return IsSubscribe;
        }
        #endregion

        #region CUSTOMGLOBALLOGIC
        public static void Custom_ApplicationStart_Logic(Object sender, EventArgs e)
        {
            // put any custom application start logic you need here...
            // do not change this routine unless you know exactly what you are doing
        }
        public static void Custom_ApplicationEnd_Logic(Object sender, EventArgs e)
        {
            // put any custom application end logic you need here...
            // do not change this routine unless you know exactly what you are doing
        }
        public static void Custom_SessionStart_Logic(Object sender, EventArgs e)
        {
            // put any custom session start logic you need here...
            // do not change this routine unless you know exactly what you are doing
        }
        public static void Custom_SessionEnd_Logic(Object sender, EventArgs e)
        {
            // put any custom session end logic you need here...
            // do not change this routine unless you know exactly what you are doing
        }
        public static void Custom_Application_Error(Object sender, EventArgs e)
        {
            // put any custom application error logic you need here...
            // do not change this routine unless you know exactly what you are doing
        }
        public static void Custom_Application_EndRequest_Logic(Object sender, EventArgs e)
        {
            // put any custom application end request logic you need here...
            // do not change this routine unless you know exactly what you are doing
        }
        public static bool Custom_Application_BeginRequest_Logic(Object sender, EventArgs e)
        {
            // put any custom application begin request logic you need here...
            // return TRUE if you do NOT want our UrlRewriter to fire
            // return FALSE if you do want our UrlRewriter to fire and handle this event
            // do not change this routine unless you know exactly what you are doing
            return false;
        }
        #endregion

        #region CheckCustomerCreditStatus
        public static bool CheckCustomerCreditStatus(Customer ThisCustomer)
        {
            if (AppLogic.AppConfigBool("AllowCreditHold"))
            {
                return false;
            }
            else
            {
                return (ThisCustomer.IsCreditOnHold);
            }
        }
        #endregion

        public static IEnumerable<ItemAttribute> GetSEImageAttributeByItemCodes(string[] lstcodes, string imgSize, string langCode)
        {
            string codes = string.Join(",", lstcodes.ToArray());
            string website = DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode);

            string seTitle = string.Empty;
            string seAltText = string.Empty;

            var lst = new List<ItemAttribute>();
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, string.Format("SELECT * FROM InventoryImageWebOptionDescription with (NOLOCK) WHERE ItemCode in ({0}) AND WebSiteCode = {1} AND LanguageCode = '{2}'", codes, website, langCode)))
                {
                    while (reader.Read())
                    {
                        string itemCode = DB.RSField(reader, "ItemCode");
                        switch (imgSize.ToUpperInvariant())
                        {
                            case "ICON":
                                seTitle = DB.RSField(reader, "SETitleIcon");
                                seAltText = DB.RSField(reader, "SEAltTextIcon");
                                break;
                            case "MEDIUM":
                                seTitle = DB.RSField(reader, "SETitleMedium");
                                seAltText = DB.RSField(reader, "SEAltTextMedium");
                                break;
                            case "LARGE":
                                seTitle = DB.RSField(reader, "SETitleLarge");
                                seAltText = DB.RSField(reader, "SEAltTextLarge");
                                break;
                        }

                        var newItem = new ItemAttribute()
                        {
                            ItemCode = itemCode,
                            Alt = seAltText.Replace("'", "''"),
                            Title = seTitle.Replace("'", "''")
                        };

                        lst.Add(newItem);
                    }
                }
            }
            return lst.AsEnumerable();
        }

        public static IEnumerable<ItemAttribute> GetSEImageAttributeByItemCode(string itemCode, string imgSize, string langCode)
        {
            string website = DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode);

            string seTitle = string.Empty;
            string seAltText = string.Empty;

            var lst = new List<ItemAttribute>();
            using (var con = DB.NewSqlConnection())
            {
                con.Open();

                string query = string.Format("SELECT * FROM InventoryImageWebOptionDescription IIWD with (NOLOCK) " +
                                " INNER JOIN InventoryOverrideImage IOI with (NOLOCK) ON IOI.ItemCode = IIWD.ItemCode AND IOI.[FileName] = IIWD.[FileName] " +
                                " WHERE IIWD.ItemCode = {0} AND " +
	                            " IIWD.WebSiteCode = {1} AND " +
	                            " IIWD.LanguageCode = {2} " +
                                " ORDER BY IOI.ImageIndex ", DB.SQuote(itemCode), website, DB.SQuote(langCode));

                using (var reader = DB.GetRSFormat(con, query))
                {
                    while (reader.Read())
                    {
                        string code = DB.RSField(reader, "ItemCode");
                        switch (imgSize.ToUpperInvariant())
                        {
                            case "ICON":
                                seTitle = DB.RSField(reader, "SETitleIcon");
                                seAltText = DB.RSField(reader, "SEAltTextIcon");
                                break;
                            case "MEDIUM":
                                seTitle = DB.RSField(reader, "SETitleMedium");
                                seAltText = DB.RSField(reader, "SEAltTextMedium");
                                break;
                            case "LARGE":
                                seTitle = DB.RSField(reader, "SETitleLarge");
                                seAltText = DB.RSField(reader, "SEAltTextLarge");
                                break;
                        }

                        var newItem = new ItemAttribute()
                        {
                            ItemCode = code,
                            Alt = seAltText.Replace("'", "''"),
                            Title = seTitle.Replace("'", "''")
                        };

                        lst.Add(newItem);
                    }
                }
            }
            return lst.AsEnumerable();
        }

        public static string GetZipSearchResultCount(string postalCode, string state, string country)
        {

            string _output = string.Empty;
            SqlConnection con = DB.NewSqlConnection();

            try
            {
                con.Open();
                string sqlQuery = string.Format("EcommerceSearchPostalCity {0}, {1}, {2}, {3}, '', 1", DB.SQuote(postalCode), DB.SQuote(country), DB.SQuote(state), DB.SQuote(postalCode));
                IDataReader reader = DB.GetRSFormat(con, sqlQuery);


                int i = 0;
                string city = string.Empty;

                while (reader.Read())
                {

                    city = DB.RSField(reader, "City");

                    if (i >= 2)
                    {
                        city = string.Empty;
                        break;
                    }

                    i++;
                }

                reader.Close();
                _output = i.ToString() + "," + city;

                /* --> 
                 
                 The following code segments verifies if result has only one record and searchable
                 
                 for example:
                 
                 -> "90210" and "90210 xxx" search strings will return the same result (1 record / berverly hills
                 -> Postal code need to be check again if it does exist in the dbo.SystemPostalCode and if the country is searchable
                    
                    # If not found: return 0 (this will trigger the address search dialog to display and will populate
                     all cities under the selected country and state (or without state)

                 */

                CountryAddressDTO thisCountry = CountryAddressDTO.Find(country);

                if (i == 1)
                {

                    sqlQuery = string.Format("SELECT * FROM SystemPostalCode with (NOLOCK) WHERE PostalCode = {0}", DB.SQuote(postalCode));
                    reader = DB.GetRSFormat(con, sqlQuery);

                    _output = "0,none";

                    if (reader.Read()) _output = i.ToString() + "," + city;

                }

                /* <--  */


            }
            catch (Exception ex)
            {

                _output = "GetZipSearchResultCount(): " + ex.Message;

            }
            finally
            {
                con.Close();
                con.Dispose();
            }


            return _output;

        }

        public static string RenderPostalCodeListing(bool searchExactMatch, string postalCode, string state, string country, int pageNo, string searchString)
        {
            //RC2 : Conver this to xml

            string outputString = string.Empty;
            var con = DB.NewSqlConnection();
            
            try
            {
                con.Open();

                string sqlQuery = string.Format("EcommerceSearchPostalCity  {5}, {0}, {1}, {2}, {3}, '', {4}", DB.SQuote(searchString), DB.SQuote(country), DB.SQuote(state), DB.SQuote(postalCode), pageNo, searchExactMatch);

                var listing = new StringBuilder();
                var reader = DB.GetRSFormat(con, sqlQuery);

                int counter = 0;
                int records = 0;

                string rowClass = String.Empty;

                while (reader.Read())
                {

                    rowClass = CommonLogic.IIF((counter % 2) == 0, "row-alt-1", "row-alt-2");

                    listing.AppendFormat("<div class='list-row' data-stateCode='{0}'>", DB.RSField(reader, "StateCode"));
                    listing.AppendFormat("<div class='rows-postal-code {0}  item-{1}-postal-code'>{2}</div>", rowClass, counter.ToString(), DB.RSField(reader, "PostalCode"));
                    listing.AppendFormat("<div class='rows-city {0} item-{1}-city'>{2}</div>", rowClass, counter.ToString(), DB.RSField(reader, "City"));
                    listing.AppendFormat("<div class='rows-state-code {0} item-{1}-state-code'>{2}</div>", rowClass, counter.ToString(), DB.RSField(reader, "County"));
                    listing.Append("</div>");

                    records = DB.RSFieldInt(reader, "Items");

                    counter++;
                }


                if (counter == 0)
                {

                    listing.Append("<div id='no-records-to-display'>");
                    listing.Append(AppLogic.GetString("createaccount.aspx.101", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                    listing.Append("</div>");
                }

                listing.AppendFormat("<div id='results-found' style='display:none'>{0}</div>", records.ToString());

                listing.AppendFormat("<div id='results-state-country' style='display:none'>{0}</div>", country);

                return listing.ToString();

            }
            catch (Exception ex)
            {
                return String.Format("renderPostalCodeListing(): {0}", ex.Message);
            }
            finally
            {
                con.Close();
                con.Dispose();
            }

        }

        public static bool IsCountryHasNoActivePostal(Address address)
        {
            var con = DB.NewSqlConnection();
            try
            {
                con.Open();

                string sqlQuery = String.Format("SELECT COUNT(1) as Postals FROM SystemPostalCode WHERE CountryCode = {0}", DB.SQuote(address.Country));
                var reader = DB.GetRSFormat(con, sqlQuery);
                
                if (reader.Read())
                {
                    if (DB.RSFieldInt(reader, "Postals") == 0) return true;
                }

            }
            catch
            {
                throw;
            }
            finally
            {
                con.Close();
                con.Dispose();
            }

            return false;
        }

        public static string GAEcommerceTracking(Customer ThisCustomer)
        {

            string _output = string.Empty;

            string OrderNumber = CommonLogic.QueryStringCanBeDangerousContent("OrderNumber", true);
            Order ord = new Order(OrderNumber);

            if (ThisCustomer.CustomerCode != ord.CustomerCode)
            {
                return string.Empty;
            }

            StringBuilder tmpS = new StringBuilder();

            try
            {

                tmpS.Clear();

                tmpS.Append("<script type=\"text/javascript\">");
                tmpS.Append("\n");
                tmpS.Append("\n");

                tmpS.Append("$(window).load(function () {");
                tmpS.Append("\n");

                string addTrans = "_gaq.push(['_addTrans',{0},{1},{2},{3},{4},{5},{6},{7}]);";

                string s = String.Format(addTrans,
                                         DB.SQuoteNotUnicode(ord.OrderNumber),
                                         DB.SQuoteNotUnicode(ord.AffiliateName),
                                         DB.SQuoteNotUnicode(Localization.CurrencyStringForGatewayWithoutExchangeRate(ord.OrderSubTotal)),
                                         DB.SQuoteNotUnicode(Localization.CurrencyStringForGatewayWithoutExchangeRate(ord.Tax)),
                                         DB.SQuoteNotUnicode(Localization.CurrencyStringForGatewayWithoutExchangeRate(ord.Freight)),
                                         DB.SQuoteNotUnicode(ord.BillingAddress.City),
                                         DB.SQuoteNotUnicode(ord.BillingAddress.State),
                                         DB.SQuoteNotUnicode(ord.BillingAddress.Country));

                tmpS.Append(s + "\n");


                string addItem = "_gaq.push(['_addItem',{0},{1},'{2}','{3}',{4},{5}]);";

                foreach (CartItem c in ord.CartItems)
                {
                    tmpS.Append(string.Format(addItem,
                    DB.SQuoteNotUnicode(ord.OrderNumber),
                    DB.SQuoteNotUnicode(c.ItemCode),
                    CommonLogic.MakeSafeJavascriptString(c.ItemName.Trim()),
                    CommonLogic.MakeSafeJavascriptString(AppLogic.GetFirstProductEntity(AppLogic.LookupHelper(EntityDefinitions.readonly_CategoryEntitySpecs.m_EntityName), c.ItemCode, false, ord.LocaleSetting).Trim()),
                    DB.SQuoteNotUnicode(Localization.CurrencyStringForGatewayWithoutExchangeRate(c.Price)),
                    DB.SQuoteNotUnicode(c.m_Quantity.ToString())
                    ));

                    tmpS.Append("\n");
                }



                tmpS.Append("\n");

                tmpS.Append("_gaq.push(['_trackTrans']);");
                tmpS.Append("\n");
                tmpS.Append("\n");

                tmpS.Append(" });");
                tmpS.Append("\n");

                tmpS.Append("</script>");
                tmpS.Append("\n");

            }
            catch (Exception ex)
            {

                _output = "renderPostalCodeListing(): " + ex.Message;

            }


            _output = tmpS.ToString();

            return _output;

        }

        public static string RenderAddressVerificationDialogHTML(bool listing)
        {

            //  this function is used to render div htmls for address verification dialog
            //  added as static token @ parser.cs and embedded on template.ascx

            StringBuilder tmpS = new StringBuilder();

            if (listing)
            {
              tmpS.AppendFormat("<div id='postal-search-engine' title='{0}' style='display:none'>", AppLogic.GetString("createaccount.aspx.95", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting, true));
                    tmpS.Append("<div class='address-verification-dialog-wrapper'>");

                        tmpS.Append("<div class='clear-both height-12'></div>");
                        tmpS.AppendFormat("<div id='search-engine-string-1'>{0}</div>", AppLogic.GetString("createaccount.aspx.96", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));

                        tmpS.Append("<div class='clear-both height-12'></div>");
                      
                        tmpS.Append("<div id='search-engine-string-2'>");
                        tmpS.AppendFormat("<a href='javascript:void(1)' id='postal-search-viewl-all'>{0}<span id='state-country'></span></a>", AppLogic.GetString("createaccount.aspx.100", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                        tmpS.Append("</div>");

                        tmpS.Append("<div class='clear-both height-5'></div>");
                        tmpS.AppendFormat("<div><div class='float-left' id='search-exact-word-checkbox-place-holder'><input type='checkbox' id='address-verifcation-search-exact-word'/></div><div class='float-left' id='search-exact-match-caption'>{0}</div></div>", AppLogic.GetString("address.cs.24", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                        tmpS.Append("<div class='clear-both height-5'></div>");

                        tmpS.Append("<div id='postal-search-text-container'>");
                            tmpS.Append("<input type='text' id='postal-search-text'/>");
                            tmpS.AppendFormat("<a href='javascript:void(1);' title='{0}' id='postal-search-go'></a>", AppLogic.GetString("createaccount.aspx.102", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                        tmpS.Append("</div>");

                        tmpS.Append("<div class='clear-both height-12'></div>");
                        
                        // search result wrapper -->

                        tmpS.Append("<div id='search-result-wrapper'>");
                            tmpS.Append("<div id='search-columns'>");
                                tmpS.AppendFormat("<div class='cols-postal-code'>{0}</div>", AppLogic.GetString("createaccount.aspx.83", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                                tmpS.AppendFormat("<div class='cols-city'>{0}</div>", AppLogic.GetString("createaccount.aspx.84", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                                tmpS.AppendFormat("<div class='cols-state-code'>{0}</div>", AppLogic.GetString("address.cs.16", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                                tmpS.Append("<div class='cols-spare'>&nbsp;</div>");
                            tmpS.Append("</div>");

                            tmpS.Append("<div class='clear-both'></div>");
                            tmpS.Append("<div id='search-results'></div>");
                        tmpS.Append("</div>");

                        // search result wrapper <--

                        // search result footer -->

                        tmpS.Append("<div id='search-result-footer'>");
                            tmpS.Append("<div id='search-pages'>Page 0 of 0</div>");
                            tmpS.AppendFormat("<div id='records-found'>0 {0}</div>", AppLogic.GetString("createaccount.aspx.98", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                            tmpS.Append("</div>");
                        tmpS.Append("</div>");
                        
                        // search result footer <--

                     tmpS.Append("<div class='clear-both'></div>");
                     tmpS.Append("<div id='search-result-pagination'>Test</div>");
                    tmpS.Append("</div>");
              
                tmpS.Append("<input type='hidden' id='address-section' value='Billing'/>");
                tmpS.AppendFormat("<div id='records-found-label' class='hidden'>{0}</div>", AppLogic.GetString("createaccount.aspx.98", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                tmpS.Append("</div>");
            }
            else
            {
                tmpS.Append("<div style='display:none;margin:auto' title='Address Verification' id='ise-address-verification'>");
                tmpS.Append("<div class='address-verification-dialog-wrapper'>");
                tmpS.Append("<div class='clear-both height-5'></div>");
                tmpS.AppendFormat("{0}", AppLogic.GetString("createaccount.aspx.114", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                tmpS.Append("<div class='clear-both height-5'></div>");
                tmpS.AppendFormat("{0}", AppLogic.GetString("createaccount.aspx.115", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                tmpS.Append("<div class='clear-both height-12'></div>");
                tmpS.Append("<div style='float:left;width:50%;'>");
                tmpS.Append("<ul class='ul-list-no-style'>");
                tmpS.AppendFormat("<li style='font-weight:bold'>{0}</li>", AppLogic.GetString("selectaddress.aspx.14", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                tmpS.Append("<li><div class='clear-both height-5'></div></li>");
                tmpS.Append("<li id='c-address'></li>");
                tmpS.Append("<li id='c-city-state-postal'></li>");
                tmpS.Append("<li>");
                tmpS.Append("<div class='clear-both height-5'></div>");
                tmpS.Append("<div class='clear-both height-12'></div>");
                tmpS.Append("<input id='select-entered-address' class='btn btn-primary' type='button' value='Select Address'/>");
                tmpS.Append("</li>");
                tmpS.Append("</ul>");
                tmpS.Append("<div class='clear-both height-12'></div>");
                tmpS.Append("</div>");
                tmpS.Append("<div style='border-left: 1px solid #CCCCCC;float: left;width: 45%;'>");
                tmpS.Append("<ul  class='ul-list-no-style'>");
                tmpS.AppendFormat("<li style='font-weight:bold'>{0}</li>", AppLogic.GetString("selectaddress.aspx.15", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting));
                tmpS.Append("<li><div class='clear-both height-5'></div></li>");
                tmpS.Append("<li id='n-address'></li>");
                tmpS.Append("<li id='n-city-state-postal'></li>");
                tmpS.Append("<li>");
                tmpS.Append("<div class='clear-both height-5'></div>");
                tmpS.Append("<div class='clear-both height-12'></div>");
                tmpS.Append("<input id='select-matching-address' class='btn btn-primary' type='button' value='Select Address'/>");
                tmpS.Append("</li>");
                tmpS.Append("</ul>");
                tmpS.Append("<div class='clear-both height-12'></div>");
                tmpS.Append("</div>");
                tmpS.Append("<div class='clear-both height-5'></div>");
                tmpS.Append("</div>");
                tmpS.Append("</div>");
            }

            return tmpS.ToString();
        }

        public static void AddItemsToDropDownList(ref DropDownList control, string listType, bool withDefault)
        {
            var con = DB.NewSqlConnection();

            try
            {
                con.Open();

                string sqlQuery = String.Empty;
                string fieldname = String.Empty;
                
                switch (listType)
                {
                    case "Country":
   
                        sqlQuery  = "SELECT CountryCode, IsWithState, IsSearchablePostal FROM ECommerceAddressCountryView";
                        fieldname = "CountryCode";

                        break;
                    case "Salutation":

                        sqlQuery  = "SELECT SalutationDescription FROM SystemSalutation with (NOLOCK) WHERE IsActive = 1";
                        fieldname = "SalutationDescription";

                        break;
                    case "Suffix":

                        sqlQuery  = "SELECT SuffixCode FROM SystemSuffix with (NOLOCK) WHERE IsActive = 1";
                        fieldname = "SuffixCode";

                        break;
                    default:

                        sqlQuery = "SELECT CountryCode, IsWithState, IsSearchablePostal FROM ECommerceAddressCountryView";
                        fieldname = "CountryCode";

                        break;
                }

                var reader = DB.GetRSFormat(con, sqlQuery.ToString());

                if (!withDefault)
                {
                    control.Items.Add(AppLogic.GetString("createaccount.aspx.81", AppLogic.GetCurrentSkinID(), Customer.Current.LocaleSetting, true));
                }

                var className = new StringBuilder();
                string value = String.Empty;

                bool isWithState = false;
                bool isSearchable = false;


                while (reader.Read())
                {

                    value = DB.RSField(reader, fieldname);
                    var listItem = new ListItem();

                    if (!string.IsNullOrEmpty(value) && value.Length > 0)
                    {
                        listItem.Value = value.ToString();

                        if (listType == "Country")
                        {

                            isWithState = DB.RSFieldBool(reader, "IsWithState");
                            isSearchable = DB.RSFieldBool(reader, "IsSearchablePostal");

                            className.AppendFormat("{0}::{1}-", isWithState.ToString().ToLowerInvariant(), isSearchable.ToString().ToLowerInvariant());
                        }

                        control.Items.Add(listItem);
                    }
                }

                if (listType == "Country")
                {
                    control.CssClass = className.ToString().TrimEnd('-');
                }

            }
            catch {

                throw;

            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }

        public static string RenderStatesOptionsHTML(string countryCode)
        {
            string states = string.Empty;

            SqlConnection con = DB.NewSqlConnection();
            
            try
            {
                con.Open();

                IDataReader reader = DB.GetRSFormat(con, "SELECT DISTINCT StateCode, State FROM SystemPostalCode with (NOLOCK) WHERE IsActive = 1 AND CountryCode = '" + countryCode + "' AND StateCode IS NOT NULL AND State IS NOT NULL ORDER BY StateCode ASC");
                while (reader.Read())
                {
                    string code = DB.RSField(reader, "StateCode");
                    string description = DB.RSField(reader, "State");

                    if (!string.IsNullOrEmpty(code) && code.Length > 0)
                    {
                        states += "<option value='" + code + "'>" + description + "</option>";
                    }
                }

            }
            catch (Exception ex)
            {
                states = "populateStates(): " + ex.Message;
            }
            finally
            {
                con.Close();
                con.Dispose();
            }


            return states;
        }

        public static string SendEmailNotification(int skinId, string localeSettings, string leadDetails)
        {

            string status = "";

            try
            {
                if (AppLogic.AppConfigBool(SEND_LF_NOTIFICATION))
                {
                    AppLogic.SendMail(
                    AppLogic.GetString(SUBJECT, skinId, localeSettings),
                    AppLogic.RunXmlPackage(AppLogic.AppConfig(XML_LF_NOTIFICATION), null, null, skinId, string.Empty, AppLogic.MakeXmlPackageParamsFromString(leadDetails), false, false),
                    true,
                    AppLogic.AppConfig(FROM_ADDRESS),
                    AppLogic.AppConfig(FROM_NAME),
                    AppLogic.AppConfig(TO_ADDRESS),
                    AppLogic.AppConfig(TO_NAME),
                    string.Empty,
                    AppLogic.AppConfig(MAIL_SERVER)
                 );

                }

            }

            catch (Exception ex)
            {

                status = ex.Message;

            }

            return status;
        }

        public static IEnumerable<SystemSalutation> GetSystemSalutationsBillingAddress()
        {
            var lstSalutations = new List<SystemSalutation>();
            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, "SELECT SalutationDescription FROM SystemSalutation with (NOLOCK) WHERE IsActive = 1"))
                {
                    while (reader.Read())
                    {
                        lstSalutations.Add(new SystemSalutation { SalutationDescription = reader["SalutationDescription"].ToString() });
                    }
                    reader.Close();
                }
            }
            return lstSalutations;
        }

        public static void UpdateAnonRecordIfIsover13checked(int isover13, int isupdated, string customerGuid)
        {
            string updateAnonRecordIfIsover13checked =
                    string.Format("UPDATE EcommerceCustomer SET IsOver13 = {0} , IsUpdated = {1} WHERE ContactGuid = {2}",
                                                DB.SQuote(isover13.ToString()),
                                                DB.SQuote(isupdated.ToString()),
                                                DB.SQuote(customerGuid));
            DB.ExecuteSQL(updateAnonRecordIfIsover13checked);
        }

        public static string GetSpecialsBoxExpandedRandom(string CategoryID, bool showPics, bool IncludeFrame, string teaser, int SkinID, string LocaleSetting, Customer ViewingCustomer, string xmlHelperDesign)
        {
            var xml = new XElement(DomainConstants.XML_ROOT_NAME);
            xml.Add(new XElement(DomainConstants.XML_SECTION_TYPE, XMLDefaultPageSectionType.GETSPECIALSBOXEXPANDEDRANDOM.ToString()));

            var package = new XmlPackage2(xmlHelperDesign, xml);
            return package.TransformString();

            var tmpS = new StringBuilder();

            string sql = string.Format("select counter, itemcode, itemname, itemdescription, webdescription, summary from EcommerceViewProduct with (NOLOCK) where published = 1 and isfeatured = 1 and CheckOutOption = 0 and shortstring = {0} AND WebSiteCode = {1} {2}", DB.SQuote(LocaleSetting), DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                         CommonLogic.IIF(!string.IsNullOrEmpty(Customer.Current.ProductFilterID), string.Format(" AND ItemCode IN (SELECT DISTINCT(ItemCode) FROM InventoryProductFilterTemplateItem WHERE TemplateID = '{0}')", Customer.Current.ProductFilterID), string.Empty));

            var ds = DB.GetDS(sql, false, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()));
            int NumRecs = ds.Tables[0].Rows.Count;
            int ShowRecNum = CommonLogic.GetRandomNumber(1, NumRecs);

            tmpS.Append("<table width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" border=\"0\">\n");
            int i = 1;
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string displayName = DB.RowField(row, "ItemDescription");
                if (CommonLogic.IsStringNullOrEmpty(displayName))
                {
                    displayName = DB.RowField(row, "ItemName");
                }

                if (i == ShowRecNum)
                {
                    tmpS.Append("<tr>");
                    string ImgUrl = string.Empty;
                    string productLink = SE.MakeProductLink(DB.RowField(row, "Counter"), displayName);

                    bool m_WatermarksEnabled = AppLogic.AppConfigBool("Watermark.Enabled");
                    if (m_WatermarksEnabled)
                    {
                        ImgUrl = string.Format("watermark.axd?counter={0}&size=icon", DB.RowFieldInt(row, "Counter").ToString());
                    }
                    else
                    {
                        ImgUrl = AppLogic.LookupImage("Product", DB.RowField(row, "Counter"), "icon", SkinID, LocaleSetting);
                    }
                    if (showPics)
                    {
                        tmpS.Append("<td align=\"left\" valign=\"top\">\n");
                        tmpS.Append("<a href=\"" + productLink + "\">");
                        tmpS.Append("<img align=\"left\" src=\"" + ImgUrl + "\" border=\"0\" />");
                        tmpS.Append("</a>");
                        tmpS.Append("</td>");
                    }

                    tmpS.Append("<td align=\"left\" valign=\"top\">\n");
                    tmpS.Append("<b class=\"a4\">");
                    tmpS.Append("<a href=\"" + productLink + "\">" + DB.RowFieldByLocale(row, "ItemDescription", LocaleSetting));
                    tmpS.Append("</a>");

                    if (DB.RowFieldByLocale(row, "Summary", LocaleSetting).Length != 0)
                    {
                        tmpS.Append("<br />" + DB.RowFieldByLocale(row, "Summary", LocaleSetting));
                    }

                    tmpS.Append("</b><br />\n");
                    if (DB.RowFieldByLocale(row, "WebDescription", LocaleSetting).Length != 0)
                    {
                        string tmpD = DB.RowFieldByLocale(row, "WebDescription", LocaleSetting);
                        if (AppLogic.ReplaceImageURLFromAssetMgr)
                        {
                            tmpD = tmpD.Replace("../images", "images");
                        }
                        tmpS.Append("<span class=\"a2\">" + tmpD + "</span><br />\n");
                    }
                    else
                    {
                        string tmpD = DB.RowFieldByLocale(row, "ItemDescription", LocaleSetting);
                        if (AppLogic.ReplaceImageURLFromAssetMgr)
                        {
                            tmpD = tmpD.Replace("../images", "images");
                        }
                        tmpS.Append("<span class=\"a2\">" + tmpD + "</span><br />\n");
                    }

                    tmpS.Append("<div class=\"a1\" style=\"PADDING-BOTTOM: 10px\">\n");
                    tmpS.Append("<a href=\"" + productLink + "\">");
                    tmpS.Append(GetString("common.cs.16", SkinID, LocaleSetting));
                    tmpS.Append("</a>");
                    tmpS.Append("</div>\n");
                    tmpS.Append("</td>");
                    tmpS.Append("</tr>");
                }
                i++;
            }

            tmpS.Append("<tr><td " + CommonLogic.IIF(showPics, "colspan=\"2\"", "") + "><hr size=\"1\" class=\"LightCellText\"/><a href=\"featureditems.aspx?resetfilter=true\">Show me more specials...</a></td></tr>");
            tmpS.Append("</table>\n");
            ds.Dispose();

            var xmlpackage = new XmlPackage2(xmlHelperDesign, xml);
            return tmpS.ToString();
        }

        public static string GetSpecialsBoxExpanded(string categoryID, int showNum, bool useCache, bool showPics, bool includeFrame, string teaser, int skinID, string localeSetting, Customer viewingCustomer, string useXmlDesign)
        {
            var xml = new XElement(DomainConstants.XML_ROOT_NAME);
            xml.Add(new XElement(DomainConstants.XML_SECTION_TYPE, XMLDefaultPageSectionType.GET_SPECIALS_BOX_EXPANDED.ToString()));

            bool showItemPrice = AppLogic.AppConfigBool("FeaturedItemsDisplayPrice");
            showPics = AppLogic.AppConfigBool("FeaturedItemsDisplayPic");

            xml.Add(new XElement("SHOWITEMPRICE", showItemPrice.ToStringLower()));
            xml.Add(new XElement("SHOWPICS", showPics.ToStringLower()));
            xml.Add(new XElement("SKINID", skinID));
            xml.Add(new XElement("LAYOUT", AppLogic.AppConfig("FeaturedItemLayout").ToUpper()));
            xml.Add(new XElement("SHOWITEMRATING", AppLogic.AppConfigBool("FeaturedItemsDisplayRating")));
            xml.Add(new XElement("ADDTOCART_ACTION", AppLogic.AppConfig("AddToCartAction")));

            string cacheName = "GetSpecialsBoxExpanded_" + categoryID.ToString() + "_" + showNum.ToString() + "_" + showPics.ToString() + "_" + teaser + "_" + skinID.ToString() + "_" + localeSetting + "_" + viewingCustomer.CurrencyCode;
            string imgFilename = string.Empty;
            string imgUrl = string.Empty;
            bool existing = false;
            bool exists = false;

            if (AppLogic.CachingOn && useCache)
            {
                string htmlTest = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(cacheName);
                if (!htmlTest.IsNullOrEmptyTrimmed()) return htmlTest;
            }

            var tmpS = new StringBuilder();

            string query = string.Format("exec EcommerceFeaturedProduct @LocaleSetting = {0}, @WebSiteCode = {1},  @CurrentDate = {2}, @ContactCode = {3}",
                    DB.SQuote(localeSetting),
                    DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                    DB.SQuote(Localization.DateTimeStringForDB(DateTime.Now)),
                    DB.SQuote(viewingCustomer.ContactCode));

            var ds = DB.GetDS(query, false);
            if (ds.Tables[0].Rows.Count > 0)
            {
                //shuffle and limit featured items display
                var lstItemCodes = ds.Tables[0].Rows.OfType<DataRow>()
                                                    .Select(r => DB.SQuote(DB.RowField(r, "ItemCode")))
                                                    .AsParallel()
                                                    .Shuffle(new Random())
                                                    .Take(AppLogic.AppConfigUSInt("NumHomePageSpecials"))
                                                    .ToArray();
                var lstOverrideImages = InterpriseHelper.GetInventoryOverideImageList(string.Join(",", lstItemCodes));
                var attList = GetSEImageAttributeByItemCodes(lstItemCodes, "ICON", AppLogic.GetLanguageCode(viewingCustomer.LocaleSetting));
                var drItems = ds.Tables[0].Rows.OfType<DataRow>().Where(r => lstItemCodes.Any(itemCode => itemCode == DB.SQuote(DB.RowField(r, "ItemCode"))));

                foreach (var row in drItems)
                {
                    var itemXml = new XElement("PRODUCT_ITEM");
                    xml.Add(itemXml);

                    int counter = DB.RowFieldInt(row, "Counter");
                    string displayName = CommonLogic.IIF(string.IsNullOrEmpty(DB.RowField(row, "ItemDescription")),
                                                        DB.RowField(row, "ItemName"),
                                                        DB.RowField(row, "ItemDescription"));
                    string itemCode = DB.RowField(row, "ItemCode");
                    string itemType = DB.RowField(row, "ItemType");

                    itemXml.Add(new XElement("COUNTER", counter));
                    itemXml.Add(new XElement("ITEMCODE", itemCode));
                    itemXml.Add(new XElement("DISPLAYNAME", Security.HtmlEncode(displayName)));
                    itemXml.Add(new XElement("DISPLAYNAME_ELLIPSES", CommonLogic.Ellipses(Security.HtmlEncode(displayName), 28, false)));
                    itemXml.Add(new XElement("ITEMTYPE", itemType.ToUpperInvariant()));

                    bool displayAddToCart = AppLogic.AppConfigBool("FeaturedItemsDisplayAddToCart");
                    if (itemType == Interprise.Framework.Base.Shared.Const.ITEM_TYPE_KIT || itemType == Interprise.Framework.Base.Shared.Const.ITEM_TYPE_MATRIX_GROUP) { displayAddToCart = false; }
                    itemXml.Add(new XElement("SHOWADDTOCART", displayAddToCart));


                    imgFilename = lstOverrideImages.FirstOrDefault(m => m.Key == itemCode).Value;
                    existing = !string.IsNullOrEmpty(imgFilename);
                    imgFilename = CommonLogic.IIF(!string.IsNullOrEmpty(imgFilename), imgFilename, string.Empty);
                    imgUrl = LocateImageFilenameUrl("product", itemCode, "icon", imgFilename, AppLogic.AppConfigBool("Watermark.Enabled"), out exists);

                    itemXml.Add(new XElement("IMAGE_URL", imgUrl));

                    var att = attList.FirstOrDefault(l => l.ItemCode == itemCode);
                    string title = string.Empty;
                    string alt = string.Empty;
                    if (att != null)
                    {
                        title = att.Title;
                        alt = att.Alt;
                    }

                    itemXml.Add(new XElement("IMAGE_TITLE", title));
                    itemXml.Add(new XElement("IMAGE_ALT", alt));
                    itemXml.Add(new XElement("PRODUCT_LINK", SE.MakeProductLink(counter.ToString(), displayName)));

                    string summary = DB.RowFieldByLocale(row, "Summary", localeSetting);
                    itemXml.Add(new XElement("SUMMARY", summary));
                    itemXml.Add(new XElement("SUMMARY_ELLIPSES", CommonLogic.Ellipses(summary, 170, false)));

                    if (showItemPrice)
                    {
                        decimal promotionalPrice = 0;
                        decimal price = 0;

                        price = Math.Round(InterpriseHelper.GetSalesPriceAndTax(Customer.Current.CustomerCode, itemCode, Customer.Current.CurrencyCode, 1, "EACH", AppLogic.AppConfigBool("VAT.Enabled"), ref promotionalPrice), 2);
                        if (promotionalPrice > 0)
                        {
                            itemXml.Add(new XElement("PROMOTIONALPRICE", InterpriseHelper.FormatCurrencyForCustomer(Math.Round(promotionalPrice, 2), Customer.Current.CurrencyCode)));
                        }
                        else if (itemType == "KIT")
                        {
                            price = Math.Round(decimal.Parse(InterpriseHelper.InventoryKitPackagePrice(itemCode, Customer.Current.CurrencyCode)), 2);
                        }

                        itemXml.Add(new XElement("PRICE", InterpriseHelper.FormatCurrencyForCustomer(price, Customer.Current.CurrencyCode)));
                    }
                }
            }

            var xmlPackage = new XmlPackage2(useXmlDesign, xml);
            string output = xmlPackage.TransformString();

            if (CachingOn && useCache)
            {
                CachingFactory.ApplicationCachingEngineInstance.AddItem(cacheName, output, AppLogic.CacheDurationMinutes());
            }

            return output;
        }

        public static string GetNewsBoxExpanded(bool LinkHeadline, bool ShowCopy, int showNum, bool IncludeFrame, bool useCache, string teaser, int SkinID, string LocaleSetting, string xmlHelperDesign)
        {
            string CacheName = "GetNewsBoxExpanded_" + showNum.ToString() + "_" + teaser + "_" + SkinID.ToString() + "_" + LocaleSetting;
            if (AppLogic.CachingOn && useCache)
            {
                string htmlTest = CachingFactory.ApplicationCachingEngineInstance.GetItem<string>(CacheName);
                if (!htmlTest.IsNullOrEmptyTrimmed()) return htmlTest;
            }

            var xml = new XElement(DomainConstants.XML_ROOT_NAME);
            xml.Add(new XElement(DomainConstants.XML_SECTION_TYPE, XMLDefaultPageSectionType.GET_NEWS_BOX_EXPANDED.ToString()));
            xml.Add(new XElement("SHOWCOPY", ShowCopy.ToStringLower()));
            xml.Add(new XElement("LINK_HEADLINE", LinkHeadline.ToStringLower()));
            xml.Add(new XElement("TEASER", teaser));

            string getAllNewsForThisWebsiteQuery = string.Format(
                                                        "exec EcommerceGetWebNews @WebsiteCode = {0}, @LanguageCode = {1}, @CurrentDate = {2}",
                                                        DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                                                        DB.SQuote(Customer.Current.LanguageCode),
                                                        DB.SQuote(Localization.ToDBDateTimeString(DateTime.Now)));

            var ds = DB.GetDS(getAllNewsForThisWebsiteQuery, AppLogic.CachingOn, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()));
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var itemXml = new XElement("NEWS_ITEM");
                    xml.Add(itemXml);

                    itemXml.Add(new XElement("DATE_CREATED", Localization.ToNativeShortDateString(DB.RowFieldDateTime(row, "DateCreated"))));
                    string headLine = DB.RowField(row, "Headline");
                    if (headLine.Length == 0)
                    {
                        headLine = CommonLogic.Ellipses(DB.RowField(row, "NewsContent"), 50, true);
                    }
                    itemXml.Add(new XElement("HEADLINE", headLine));
                    itemXml.Add(new XElement("ITEM_COUNTER", DB.RowField(row, "Counter")));
                    itemXml.Add(new XElement("NEWS_CONTENT", HttpContext.Current.Server.HtmlDecode(DB.RowField(row, "NewsContent"))));
                }
            }

            var package = new XmlPackage2(xmlHelperDesign, xml);
            string output = package.TransformString();

            if (CachingOn && useCache)
            {
                CachingFactory.ApplicationCachingEngineInstance.AddItem(CacheName, output, AppLogic.CacheDurationMinutes());
            }

            return output;

        }

        public static void DoActiveShoppersProcess()
        {
            //test if websupport is enabled
            bool? enableWebSupport = AppLogic.AppConfig("WebSupport.Enabled").TryParseBool();
            if ((!enableWebSupport.HasValue) || (enableWebSupport.HasValue && !enableWebSupport.Value)) return;

            //test if query string has the valid value
            string requestCode = Interprise.Framework.ECommerce.Const.TableColumns.ACTIVESHOPPERS_QUERYSTRING.ToQueryString();
            if (requestCode.IsNullOrEmptyTrimmed()) return;

            //get the contact based from the code
            var contactGuid = InterpriseSuiteEcommerceCommon.DataAccess.ActiveShopperDA.GetContactCodeByActiveShoppersCode(requestCode);

            //check if the code is valid
            if (!contactGuid.HasValue) return;

            //remove the code from the table.
            //DeleteShoppersByRequestCode(requestCode);

            var foundCustomer = Customer.Find(contactGuid.Value);
            HttpContext.Current.User = new InterpriseSuiteEcommercePrincipal(foundCustomer);
            if (foundCustomer != null)
            {
                foundCustomer.ReInitCustomerForActiveShoppers();
            }

            int? timeLimit = AppLogic.AppConfig("WebSupport.Time").TryParseInt();
            if (!timeLimit.HasValue) { timeLimit = 3; }

            //to remove the query string from the url
            CurrentContext.Redirect(CurrentContext.FullyQualifiedApplicationPath());
        }

        public static string RenderMobileSwitcherLink(bool isFullMode) 
        { 
            var fields = new XElement(DomainConstants.XML_ROOT_NAME);
            fields.Add(new XElement(DomainConstants.XML_SECTION_TYPE, XMLSectionType.DISPLAY_MOBILE_FULLMODE_SWITCHING_LINK));
            fields.Add(new XElement("ISINFULLMODE", isFullMode.ToStringLower()));

            var xmlPackageRenderer = new XmlPackage2("helper.page.default.xml.config", fields);
            return xmlPackageRenderer.TransformString();
        }

        /// <summary>
        /// Get Credit Card Type information.
        /// </summary>
        /// <param name="newRow">Additional row to insert before loading the data from database.</param>
        /// <returns></returns>
        public static DataView GetCustomerCreditCardType(string newRow)
        {
            var dt = new DataTable();
            dt.Columns.Add(new DataColumn("CreditCardType", typeof(string)));
            dt.Columns.Add(new DataColumn("CreditCardTypeDescription", typeof(string)));

            var dr = dt.NewRow();
            dr["CreditCardType"] = newRow;
            dr["CreditCardTypeDescription"] = newRow;
            dt.Rows.Add(dr);

            using (var con = DB.NewSqlConnection())
            {
                con.Open();
                using (var reader = DB.GetRSFormat(con, "SELECT CreditCardType, CreditCardTypeDescription FROM CustomerCreditCardType with (NOLOCK) WHERE IsActive = 1"))
                {
                    dt.Load(reader);
                }
            }
            return dt.DefaultView;
        }

        /// <summary>
        /// Clears the card info of the customer's creditcard
        /// </summary>
        /// <param name="CreditCardCode"></param>
        public static void ClearCreditCardInfo(string CreditCardCode)
        {
            DB.ExecuteSQL("UPDATE CustomerCreditCard SET CreditCardDescription=NULL, MaskedCardNumber=NULL, InterpriseGatewayRefNo=NULL, InterpriseGatewayRefNoDate=NULL,Vault=NULL WHERE CreditCardCode={0}", DB.SQuote(CreditCardCode));
        }

        /// <summary>
        /// Checks if webstore is using InterpriseGatewayV2
        /// </summary>
        /// <returns></returns>
        public static bool IsUsingInterpriseGatewayv2()
        {
            string gateway = string.Empty;

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader reader = DB.GetRSFormat(con, "SELECT CreditCardGateway FROM ECommerceSite with (NOLOCK) WHERE WebSiteCode = {0}", DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode)))
                {
                    if (reader.Read())
                    {
                        gateway = DB.RSField(reader, "CreditCardGateway");
                    }
                }
            }

            if (gateway == ro_INTERPRISE_GATEWAY_V2)
            {
                return true;
            }

            return false;
        }

        public static bool IsCBNMode()
        {
            bool cbMode;
            bool.TryParse(AppLogic.ReadCookie(ro_CBN_MODE), out cbMode);
            return cbMode;
        }

        public static string GetCustomerCreditCardMaskedCardNumber()
        {

            string maskedCardNumber = string.Empty;

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader reader = DB.GetRSFormat(con, "SELECT MaskedCardNumber FROM CustomerCreditCard with (NOLOCK) WHERE CreditCardCode={0}", DB.SQuote(Customer.Current.PrimaryBillingAddress.AddressID)))
                {
                    if (reader.Read())
                    {
                        maskedCardNumber = DB.RSField(reader, "MaskedCardNumber");
                    }
                }

            }

            if (string.IsNullOrEmpty(maskedCardNumber)) maskedCardNumber = string.Empty;

            return maskedCardNumber;
        }

        public static decimal GetKitItemPrice(string itemCode, string itemType, string unitMeasureCode, string composition)
        {
            // NOTE:
            //  Currently, only kit type products use this web service
            if (itemType == Interprise.Framework.Base.Shared.Const.ITEM_TYPE_KIT)
            {
                var thisCustomer = Customer.Current;
                var selectedComposition = KitComposition.FromComposition(composition, thisCustomer, CartTypeEnum.ShoppingCart, itemCode);
                selectedComposition.UnitMeasureCode = unitMeasureCode;
                var nfo = UnitMeasureInfo.ForItem(itemCode, unitMeasureCode);
                selectedComposition.Quantity = decimal.One * nfo.Quantity;

                if (selectedComposition != null)
                {
                    decimal vat = decimal.Zero;
                    decimal price = selectedComposition.GetSalesPrice(ref vat);

                    return price;
                }
            }

            return decimal.Zero;
        }

        public static void AddKitItem(Guid? cartID, string customerCode, string itemKitCode, Guid? giftRegistryID, Guid? registryItemCode, List<KitCartItem> compositions)
        {
            using (var con = new SqlConnection(DB.GetDBConn()))
            {
                con.Open();

                using (var cmdCreateKitCart = new SqlCommand("EcommerceCreateKitCartItem", con))
                {
                    cmdCreateKitCart.CommandType = CommandType.StoredProcedure;
                    var paramCustomerCode = new SqlParameter("@CustomerCode", SqlDbType.NVarChar, 30);
                    var paramItemKitCode = new SqlParameter("@ItemKitCode", SqlDbType.NVarChar, 30);
                    var paramKitItemCounter = new SqlParameter("@KitItemCode", SqlDbType.NVarChar, 30);
                    var paramKitGroupCounter = new SqlParameter("@KitGroupCode", SqlDbType.NVarChar, 30);
                    var paramCreatedOn = new SqlParameter("@CreatedOn", SqlDbType.SmallDateTime);

                    if (cartID.HasValue)
                    {
                        var paramCartID = new SqlParameter("@CartID", SqlDbType.UniqueIdentifier);
                        cmdCreateKitCart.Parameters.Add(paramCartID);
                        paramCartID.Value = cartID.Value;
                    }

                    if (registryItemCode.HasValue)
                    {
                        var paramGiftRegistryID = new SqlParameter("@GiftRegistryID", SqlDbType.UniqueIdentifier);
                        cmdCreateKitCart.Parameters.Add(paramGiftRegistryID);
                        paramGiftRegistryID.Value = giftRegistryID.Value;

                        var paramGiftRegistryItemCode = new SqlParameter("@RegistryItemCode", SqlDbType.UniqueIdentifier);
                        cmdCreateKitCart.Parameters.Add(paramGiftRegistryItemCode);
                        paramGiftRegistryItemCode.Value = registryItemCode.Value;
                    }

                    cmdCreateKitCart.Parameters.Add(paramCustomerCode);
                    cmdCreateKitCart.Parameters.Add(paramItemKitCode);
                    cmdCreateKitCart.Parameters.Add(paramKitItemCounter);
                    cmdCreateKitCart.Parameters.Add(paramKitGroupCounter);
                    cmdCreateKitCart.Parameters.Add(paramCreatedOn);

                    paramCustomerCode.Value = customerCode;
                    paramItemKitCode.Value = itemKitCode;
                    paramCreatedOn.Value = DateTime.Now;

                    foreach (var kitItem in compositions)
                    {
                        paramKitItemCounter.Value = kitItem.ItemCode;
                        paramKitGroupCounter.Value = kitItem.GroupCode;
                        cmdCreateKitCart.ExecuteNonQuery();
                    }
                }
            }
        }

        public static void SendMailRequest(string subject, string body, bool useHTML)
        {
            string[] emailacctinfo = InterpriseHelper.GetStoreEmailAccountInfo();
            if (!string.IsNullOrEmpty(emailacctinfo[0]))
            {
                SendMailRequest(subject, body, useHTML, emailacctinfo[0], emailacctinfo[1], emailacctinfo[0], emailacctinfo[1], string.Empty);
            }
        }

        public static void SendMailRequest(string subject, string body, bool useHTML, string fromemailacccode, string fromname, string toaddress, string toname, string bccaddresses)
        {
            SendMailRequest(subject, body, useHTML, fromemailacccode, fromname, toaddress, toname, bccaddresses, string.Empty, string.Empty, false, false, false);
        }

        public static void SendMailRequest(string subject, string body, bool useHTML, string fromemailacccode, string fromname, string toaddress, string toname, string bccaddresses, bool throwError)
        {
            SendMailRequest(subject, body, useHTML, fromemailacccode, fromname, toaddress, toname, bccaddresses, string.Empty, string.Empty, false, false, throwError);
        }

        public static void SendMailRequest(string subject, string body, bool useHTML, string fromemailacccode, string fromname, string toaddress, string toname, string bccaddresses, string ReplyTo, string orderNumber, bool createAttachment, bool multipleAttachment)
        {
            SendMailRequest(subject, body, useHTML, fromemailacccode, fromname, toaddress, toname, bccaddresses, ReplyTo, orderNumber, createAttachment, multipleAttachment, false);
        }

        // mask errors on store site, better to have a lost receipt than crash the site
        // on admin site, throw exceptions
        public static void SendMailRequest(string subject, string body, bool useHTML, string fromemailacccode, string fromname, string toaddress, string toname, string bccaddresses, string ReplyTo, string orderNumber, bool createAttachment, bool multipleAttachment, bool throwError)
        {
            Interprise.Facade.Base.CRM.Connect.EMailMessageFacade emailfacade;
            Interprise.Licensing.Base.Connect.EMailMessage emailMessage;
            string errormsg = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(fromemailacccode) || Interprise.Framework.Base.Shared.Common.IsValidEmail(fromemailacccode))
                {
                    string[] defaultemailacctinfo = InterpriseHelper.GetStoreEmailAccountInfo();
                    fromemailacccode = defaultemailacctinfo[0];
                }

                if (!string.IsNullOrEmpty(fromemailacccode))
                {
                    emailfacade = new Interprise.Facade.Base.CRM.Connect.EMailMessageFacade();
                    emailMessage = new Interprise.Licensing.Base.Connect.EMailMessage();

                    // add EmailTo
                    
                    if (toaddress.Length != 0)
                    {
                        string[] emailadds = toaddress.Split(new char[] { ',', ';' });
                        string[] names = toname.Split(new char[] { ',', ';' });
                        int emailIndex = -1;

                        foreach (string emailadd in emailadds)
                        {
                            if (Interprise.Framework.Base.Shared.Common.IsValidEmail(emailadd))
                            {
                                emailIndex = Array.IndexOf(emailadds, emailadd);
                                if (emailIndex > -1 && names.Length >= (emailIndex + 1))
                                {
                                    if (names[emailIndex] == emailadd)
                                    {
                                        emailMessage.AddTo(string.Empty, emailadd);
                                    }
                                    else
                                    {
                                        emailMessage.AddTo(names[emailIndex], emailadd);
                                    }
                                }
                                else
                                {
                                    emailMessage.AddTo(string.Empty, emailadd);
                                }

                            }
                        }
                    }

                    // add reply to 
                    if (ReplyTo.Length != 0)
                    {
                        string[] emailReplyToadds = ReplyTo.Split(new char[] { ',', ';' });
                        foreach (string emailrepadd in emailReplyToadds)
                        {
                            if (Interprise.Framework.Base.Shared.Common.IsValidEmail(emailrepadd))
                            {
                                emailMessage.ReplyTo = emailrepadd;
                            }
                        }
                    }

                    // add subject 
                    emailMessage.Subject = subject;

                    // add body
                    if (useHTML)
                    {
                        emailMessage.SetHtmlBody(body);
                    }
                    else
                    {
                        emailMessage.Body = body;
                    }

                    // add bcc to 
                    if (bccaddresses.Length != 0)
                    {
                        string[] emailBccToadds = bccaddresses.Split(new char[] { ',', ';' });
                        foreach (string emailbccadd in emailBccToadds)
                        {
                            if (Interprise.Framework.Base.Shared.Common.IsValidEmail(emailbccadd))
                            {
                                emailMessage.AddBcc(string.Empty, emailbccadd);
                            }
                        }
                    }

                    // Create  the file attachment for this e-mail message.
                    string attchfilename = string.Empty;
                    List<string> attchfilenames = new List<string>();
                    if (createAttachment)
                    {
                        if (multipleAttachment)
                        {
                            foreach (string singleOrderNumber in orderNumber.Split(','))
                            {
                                Attachment reportAttachment = InterpriseHelper.ExportReportAsAttachment(singleOrderNumber);
                                attchfilename = System.IO.Path.GetTempPath() + reportAttachment.ContentType.Name;
                                if (System.IO.File.Exists(attchfilename)) { System.IO.File.Delete(attchfilename); }
                                if (!System.IO.File.Exists(attchfilename))
                                {
                                    var filestream = System.IO.File.Create(attchfilename);
                                    reportAttachment.ContentStream.CopyTo(filestream);
                                    filestream.Close();
                                    emailMessage.AddRelatedFile(attchfilename);
                                    attchfilenames.Add(attchfilename);
                                }

                            }
                        }
                        else
                        {
                            Attachment reportAttachment = InterpriseHelper.ExportReportAsAttachment(orderNumber);
                            attchfilename = System.IO.Path.GetTempPath() + reportAttachment.ContentType.Name;
                            if (System.IO.File.Exists(attchfilename)) { System.IO.File.Delete(attchfilename); }
                            if (!System.IO.File.Exists(attchfilename))
                            {
                                var filestream = System.IO.File.Create(attchfilename);
                                reportAttachment.ContentStream.CopyTo(filestream);
                                filestream.Close();
                                emailMessage.AddRelatedFile(attchfilename);
                                attchfilenames.Add(attchfilename);
                            }
                        }
                    }
                    //get user code of email
                    string[] emailacctinfo = InterpriseHelper.GetStoreEmailAccountInfo();
                    emailfacade.LoadUserEmailAccount(emailacctinfo[2], emailacctinfo[0], false);
                    String[] messagecodes = new String[] { };
                    try
                    {
                        if (emailfacade.SaveToFolder(fromemailacccode, Interprise.Framework.Base.Shared.Const.OUTBOX_FOLDER, Interprise.Framework.Base.Shared.Enum.EMailStatus.ReadyToSend, ref messagecodes, emailMessage.GetMime()))
                        {
                            if (messagecodes.Length > 0)
                            {
                                emailMessage.AddHeaderField(Interprise.Framework.Base.Shared.Const.CONNECTMESSAGEHEADER_MESSAGECODE_COLUMN, messagecodes[0]);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        errormsg = ex.Message;
                        if (throwError && errormsg.Length > 0)
                        {
                            throw new ArgumentException("Send Email Request Error: " + errormsg);
                        }
                    }
                    finally
                    {
                        //delete created files
                        foreach (string f in attchfilenames)
                        {
                            if (System.IO.File.Exists(f)) { System.IO.File.Delete(f); }
                        }
                    }

                }
                else
                {
                    errormsg = "Invalid Email Account Code";
                }

            }
            catch (Exception ex)
            {
                errormsg = ex.Message;
                if (throwError && errormsg.Length > 0)
                {
                    throw new ArgumentException("Send Email Request Error: " + errormsg);
                }
            }

        }

        public static string GetCustomerCreditCardMaskedCardNumber(string cardCode)
        {

            var maskedCardNumber = string.Empty;

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader reader = DB.GetRSFormat(con, "SELECT MaskedCardNumber FROM CustomerCreditCard with (NOLOCK) WHERE CreditCardCode={0}", DB.SQuote(cardCode)))
                {
                    if (reader.Read())
                    {
                        maskedCardNumber = DB.RSField(reader, "MaskedCardNumber");
                    }
                }

            }

            if (string.IsNullOrEmpty(maskedCardNumber)) maskedCardNumber = string.Empty;

            return maskedCardNumber;
        }

        public static List<string> GetAddressMatch(string address, string country, string postal, string city, string state, bool isResidenceType)
        {
            var details = new List<string>();

        
            Interprise.Facade.Base.Shipping.AddressVerificationFacade m_addressVerificationFacade;
            m_addressVerificationFacade = new Interprise.Facade.Base.Shipping.AddressVerificationFacade();

            if (m_addressVerificationFacade.ValidateAddress(address, string.Empty, city.Trim(), state.Trim(), postal.Trim(), country, isResidenceType))
            {
                string addressColumnName = m_addressVerificationFacade.AddressVerificationDatasetGateway.AddressMatchDetail.Address1Column.ColumnName;
                string _address = m_addressVerificationFacade.AddressVerificationDatasetGateway.AddressMatchDetail[0][addressColumnName].ToString();

                string cityColumnName = m_addressVerificationFacade.AddressVerificationDatasetGateway.AddressMatchDetail.CityColumn.ColumnName;
                string _city = m_addressVerificationFacade.AddressVerificationDatasetGateway.AddressMatchDetail[0][cityColumnName].ToString();

                string stateColumnName = m_addressVerificationFacade.AddressVerificationDatasetGateway.AddressMatchDetail.StateColumn.ColumnName;
                string _state = m_addressVerificationFacade.AddressVerificationDatasetGateway.AddressMatchDetail[0][stateColumnName].ToString();

                string postalCodeColumnName = m_addressVerificationFacade.AddressVerificationDatasetGateway.AddressMatchDetail.PostalCodeColumn.ColumnName;
                string _postalCode = m_addressVerificationFacade.AddressVerificationDatasetGateway.AddressMatchDetail[0][postalCodeColumnName].ToString();

                string countryCodeColumnName = m_addressVerificationFacade.AddressVerificationDatasetGateway.AddressMatchDetail.CountryCodeColumn.ColumnName;
                string _countryCode = m_addressVerificationFacade.AddressVerificationDatasetGateway.AddressMatchDetail[0][countryCodeColumnName].ToString();

                details.Add(_address);
                details.Add(_postalCode);
                details.Add(_city);
                details.Add(_state);
                details.Add(_countryCode);

            }

            return details;

        }

        public static string ResolvePayPalAddressCode(string Country)
        {
            string PayPalAdCode = string.Empty;
            if (Country.Equals("GR"))
            {
                PayPalAdCode = "EL";
            }
            else if (Country.Equals("South Korea"))
            {
                PayPalAdCode = "Korea, Republic of";
            }
            else if (Country.Equals("United States"))
            {
                PayPalAdCode = "United States of America";
            }
            else
            {
                PayPalAdCode = Country;
            }

            return PayPalAdCode;
        }

        public static string GetItemPopup(string itemCode)
        {
            string result = String.Empty;

            try
            {
                var thisCustomer = Customer.Current;
                var product = AppLogic.GetProductInfoViewForShowProduct(DB.SQuote(itemCode),
                                                                                   DB.SQuote(thisCustomer.LocaleSetting),
                                                                                   DB.SQuote(InterpriseHelper.ConfigInstance.UserCode),
                                                                                   DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                                                                                   DB.SQuote(Localization.DateTimeStringForDB(DateTime.Now)),
                                                                                   DB.SQuote(thisCustomer.ProductFilterID),
                                                                                   DB.SQuote(thisCustomer.ContactCode));

                //not yet supported

                if (product == null) return String.Empty;
                if (product.CheckOutOption) return String.Empty;
                if (product.IsCBN == false && AppLogic.IsCBNMode()) return String.Empty;

                
                var xml = new XElement(DomainConstants.XML_ROOT_NAME);

                xml.Add(new XElement("SKIN_ID", AppLogic.GetCurrentSkinID()));
                xml.Add(new XElement("COUNTER", product.Counter));
                xml.Add(new XElement("ITEM_TYPE", product.ItemType));
                xml.Add(new XElement("ITEM_CODE", itemCode));
                xml.Add(new XElement("DISPLAY_NAME", (product.ItemDescription.IsNullOrEmptyTrimmed()) ? product.ItemName.Trim() : product.ItemDescription.Trim()));
                xml.Add(new XElement("DESCRIPTION", product.WebDescription));
                xml.Add(new XElement("SUMMARY", product.Summary));
                xml.Add(new XElement("WARRANTY", product.Warranty));
                xml.Add(new XElement("EXPSHIPDATE", product.ExpectedShippingDate));
                xml.Add(new XElement("DISPLAY_CONTENT", (product.RequiresRegistration) ? thisCustomer.IsRegistered : true));

                xml.Add(new XElement("REGISTERED", thisCustomer.IsRegistered));
                xml.Add(new XElement("RETURN_URL", "signin.aspx?returnurl={0}?itempopup={1}".FormatWith(Path.GetFileName(HttpContext.Current.Request.UrlReferrer.GetLeftPart(UriPartial.Path)), itemCode)));
                xml.Add(new XElement("DISPLAY_PRODUCTNAVLINKS", (CommonLogic.PageReferrer().ToLowerInvariant().Contains("default.aspx")) ? false : true));

                xml.Add(new System.Xml.Linq.XElement("DEFAULT_IMAGES"));
                foreach (var imgDefault in ProductImage.LocateDefaultImageInSizes(DomainConstants.EntityProduct, itemCode))
                {
                    var img = new System.Xml.Linq.XElement(imgDefault.ImageSizeType.ToString().ToUpper());
                    img.Add(new System.Xml.Linq.XElement("SRC", imgDefault.src));
                    img.Add(new System.Xml.Linq.XElement("TITLE", imgDefault.Title));
                    img.Add(new System.Xml.Linq.XElement("ALT", imgDefault.Alt));
                    xml.Element("DEFAULT_IMAGES").Add(img);
                }
                
                var rating = RatingCollection.ForItem(itemCode);
                xml.Add(new System.Xml.Linq.XElement("RATING_AVERAGE", rating.AverageRating));

                var xmlpackage = new XmlPackage2("page.itempopup.xml.config", xml);
                result = xmlpackage.TransformString();
            }
            catch
            {
                throw;
            }
            return result;
        }

        public static string GetItemReviews(string itemCode, int sort)
        {
            int skinID = AppLogic.GetCurrentSkinID();
            var xml = new System.Xml.Linq.XElement(DomainConstants.XML_ROOT_NAME);
            xml.Add(new System.Xml.Linq.XElement(DomainConstants.XML_SECTION_TYPE, XMLSectionType.DISPLAY_REVIEWS));
            xml.Add(new System.Xml.Linq.XElement("CUSTOMERCODE", Customer.Current.CustomerCode));
            xml.Add(new System.Xml.Linq.XElement("CONTACTCODE", Customer.Current.ContactCode));
            xml.Add(new System.Xml.Linq.XElement("CUSTOMER_REGISTERED", Customer.Current.IsRegistered));
            xml.Add(new System.Xml.Linq.XElement("ITEMCODE", itemCode));
            xml.Add(new System.Xml.Linq.XElement("SORTING_DEFAULT", sort));
            xml.Add(new System.Xml.Linq.XElement("SKIN_ID", skinID));
            xml.Add(new System.Xml.Linq.XElement("LISTONLY", 1));

            var xmlReviews = new System.Xml.Linq.XElement("REVIEWS");
            RatingCollection ratings = RatingCollection.ForItem(itemCode);

            //default sorting
            switch (sort)
            {
                case 1: //HelpfulToLessHelpful
                    ratings.Sort(new HelpfulToLessHelpfulRatingSorter());
                    break;
                case 2: //LessHelpfulToHelpful 
                    ratings.Sort(new LessHelpfulToHelpfulRatingSorter());
                    break;
                case 4: //NewToOld 
                    ratings.Sort(new NewToOldRatingSorter());
                    break;
                case 8: //OldToNew 
                    ratings.Sort(new OldToNewRatingSorter());
                    break;
                case 16: //HighToLow 
                    ratings.Sort(new HighToLowRatingSorter());
                    break;
                case 32: //LowToHigh 
                    ratings.Sort(new LowToHighRatingSorter());
                    break;
            }

            foreach (var rating in ratings.Items)
            {
                var xmlReview = new System.Xml.Linq.XElement("REVIEW");
                xmlReview.Add(new System.Xml.Linq.XElement("LAST_NAME", rating.CustomerLastName));
                xmlReview.Add(new System.Xml.Linq.XElement("FIRST_NAME", rating.CustomerFirstName));
                xmlReview.Add(new System.Xml.Linq.XElement("COMMENT", rating.Comment));
                xmlReview.Add(new System.Xml.Linq.XElement("RATING", rating.ActualRating));
                xmlReview.Add(new System.Xml.Linq.XElement("RATING_STARS", CommonLogic.BuildStarsImage(Convert.ToDecimal(rating.ActualRating), skinID)));
                xmlReview.Add(new System.Xml.Linq.XElement("DATE_CREATED", rating.CreatedOn.ToShortDateString()));
                xmlReview.Add(new System.Xml.Linq.XElement("HELPFUL_COUNT", rating.HelpfulCount));
                xmlReview.Add(new System.Xml.Linq.XElement("NOTHELPFUL_COUNT", rating.NotHelpfulCount));
                xmlReview.Add(new System.Xml.Linq.XElement("REVIEWER_CUSTOMERCODE", rating.CustomerCode));
                xmlReview.Add(new System.Xml.Linq.XElement("REVIEWER_CONTACTCODE", rating.ContactCode));
                xmlReviews.Add(xmlReview);
            }
            xml.Add(xmlReviews);

            var xmlpackage = new XmlPackage2("helper.product.xml.config", xml);
            return xmlpackage.TransformString();
        }

        public static bool HasItemReview(string itemCode, Customer customer = null)
        {
            bool hasReview = false;
            var ThisCustomer = (customer != null) ? customer : Customer.Current;
            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, String.Format(@"SELECT * FROM EcommerceRating with (NOLOCK) 
                                                                            WHERE   CustomerCode={0} AND 
                                                                                    ItemCode={1} AND 
                                                                                    WebsiteCode={2} AND 
                                                                                    ContactCode={3}",
                                                            DB.SQuote(ThisCustomer.CustomerCode), 
                                                            DB.SQuote(itemCode), 
                                                            DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode), 
                                                            DB.SQuote(ThisCustomer.ContactCode))))
                {
                    if (rs.Read())
                    {
                        hasReview = true;
                    }
                }
            }
            return hasReview;
        }

        public static void CreateItemReview(string itemCode, int rating, string comment)
        {
            var ThisCustomer = Customer.Current;
            string sql = string.Format(@"INSERT INTO EcommerceRating (
                                            ItemCode, 
                                            IsFilthy, 
                                            CustomerCode, 
                                            CreatedOn, 
                                            Rating, 
                                            HasComment, 
                                            WebSiteCode,
                                            Comments, 
                                            ContactCode) 
                                        VALUES({0},{1},{2},{3},{4},{5},{6},{7},{8})",
                                            DB.SQuote(itemCode),
                                            0,
                                            DB.SQuote(ThisCustomer.CustomerCode),
                                            DB.SQuote(Localization.ToDBDateTimeString(DateTime.Now)),
                                            rating,
                                            "1",
                                            DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                                            DB.SQuote(comment),
                                            DB.SQuote(ThisCustomer.ContactCode));
            DB.ExecuteSQL(sql);
        }

        public static void UpdateItemReview(string itemCode, int rating, string comment)
        {
            var ThisCustomer = Customer.Current;
            string sql = string.Format(@"   UPDATE EcommerceRating 
                                            SET   IsFilthy={0}, 
                                                Rating={1}, 
                                                CreatedOn=getdate(), 
                                                HasComment={2}, 
                                                Comments={3}
                                            WHERE ItemCode={4} AND 
                                                CustomerCode={5} AND 
                                                ContactCode={6} ", 
                                                0, 
                                                rating, 
                                                "1", 
                                                DB.SQuote(comment), 
                                                DB.SQuote(itemCode), 
                                                DB.SQuote(ThisCustomer.CustomerCode), 
                                                DB.SQuote(ThisCustomer.ContactCode));
            DB.ExecuteSQL(sql);
        }

        public static void VoteItemReview(string itemCode, string voterCustomerCode, string voterContactCode, string vote, string customerCode, string contactCode)
        {
            int isHelpful = CommonLogic.IIF(vote == "YES", 1, 0);
            bool isAlreadyVoted = false;

            using (SqlConnection con = DB.NewSqlConnection())
            {
                con.Open();
                using (IDataReader rs = DB.GetRSFormat(con, "SELECT * FROM EcommerceRatingCommentHelpfulness WITH (NOLOCK) WHERE ItemCode={0} AND RatingCustomerCode={1} AND RatingContactCode={2} AND VotingCustomerCode={3} AND VotingContactCode={4}", 
                                                            DB.SQuote(itemCode), 
                                                            DB.SQuote(customerCode), 
                                                            DB.SQuote(contactCode), 
                                                            DB.SQuote(voterCustomerCode), 
                                                            DB.SQuote(voterContactCode)))
                {
                    if (rs.Read())
                    {
                        isAlreadyVoted = true;
                        
                        // they have already voted on this comment, and are changing their minds perhaps, so adjust totals, and reapply vote:
                        if (DB.RSFieldBool(rs, "Helpful"))
                        {
                            DB.ExecuteSQL("UPDATE EcommerceRating SET FoundHelpful = FoundHelpful-1 WHERE ItemCode={0} AND CustomerCode={1} AND ContactCode={2}",
                                            DB.SQuote(itemCode),
                                            DB.SQuote(customerCode),
                                            DB.SQuote(contactCode));
                        }
                        else
                        {
                            DB.ExecuteSQL("UPDATE EcommerceRating SET FoundNotHelpful = FoundNotHelpful-1 WHERE ItemCode={0} AND CustomerCode={1} AND ContactCode={2}",
                                            DB.SQuote(itemCode),
                                            DB.SQuote(customerCode),
                                            DB.SQuote(contactCode));
                        }
                    }
                }
            }

            if (isAlreadyVoted)
            {
                DB.ExecuteSQL("DELETE FROM EcommerceRatingCommentHelpfulness WHERE ItemCode={0} AND RatingCustomerCode={1} AND RatingContactCode={2} AND  VotingCustomerCode={3} AND VotingContactCode={4}",
                              DB.SQuote(itemCode),
                              DB.SQuote(customerCode),
                              DB.SQuote(contactCode),
                              DB.SQuote(voterCustomerCode),
                              DB.SQuote(voterContactCode));
                
            }

            DB.ExecuteSQL(@"INSERT INTO EcommerceRatingCommentHelpfulness(ItemCode,RatingCustomerCode,VotingCustomerCode,Helpful, WebsiteCode,RatingContactCode,VotingContactCode)
                            VALUES ({0},{1},{2},{3},{4},{5},{6})",
                                                                 DB.SQuote(itemCode),
                                                                 DB.SQuote(customerCode),
                                                                 DB.SQuote(voterCustomerCode),
                                                                 isHelpful.ToString(),
                                                                 DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                                                                 DB.SQuote(contactCode),
                                                                 DB.SQuote(voterContactCode));
                
            if (vote == "YES")
            {
                DB.ExecuteSQL("UPDATE EcommerceRating SET FoundHelpful = FoundHelpful+1 WHERE ItemCode={0} AND CustomerCode={1} AND ContactCode={2}",
                    DB.SQuote(itemCode),
                    DB.SQuote(customerCode),
                    DB.SQuote(contactCode));
            }
            else
            {
                DB.ExecuteSQL("UPDATE EcommerceRating SET FoundNotHelpful = FoundNotHelpful+1 WHERE ItemCode={0} AND CustomerCode={1} AND ContactCode={2}",
                    DB.SQuote(itemCode),
                    DB.SQuote(customerCode),
                    DB.SQuote(contactCode));
            }
        }

        public static string GetProductImage(string itemCode)
        {
            Customer thisCustomer = Customer.Current;

            var product = AppLogic.GetProductInfoViewForShowProduct(DB.SQuote(itemCode),
                                                                               DB.SQuote(thisCustomer.LocaleSetting),
                                                                               DB.SQuote(InterpriseHelper.ConfigInstance.UserCode),
                                                                               DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode),
                                                                               DB.SQuote(Localization.DateTimeStringForDB(DateTime.Now)),
                                                                               DB.SQuote(thisCustomer.ProductFilterID),
                                                                               DB.SQuote(thisCustomer.ContactCode));

            var xml = new XElement(DomainConstants.XML_ROOT_NAME);
            xml.Add(new XElement(DomainConstants.XML_SECTION_TYPE, XMLSectionType.DISPLAY_PRODUCTIMAGE));
            xml.Add(new XElement("PAGINATION", (AppLogic.AppConfig("ProductImage.Pagination").IsNullOrEmptyTrimmed()) ? "thumbnail" : AppLogic.AppConfig("ProductImage.Pagination")));
            xml.Add(new XElement("SWITCHING", (AppLogic.AppConfig("ProductImage.Switching").IsNullOrEmptyTrimmed()) ? "onmouseover" : AppLogic.AppConfig("ProductImage.Switching")));
            xml.Add(new XElement("ITEM_CODE", itemCode));
            xml.Add(new XElement("ITEM_TYPE", product.ItemType));

            var imgData = ProductImageData.Get(product.Counter, itemCode, product.ItemType, 0);
            var imgDefault = ProductImage.LocateDefaultImage(DomainConstants.EntityProduct, itemCode, "MEDIUM", thisCustomer.LanguageCode);
            int imgCount = imgData.mediumImages.Count;
            int displayLimit = (AppLogic.AppConfig("ProductImage.DisplayLimit").IsNullOrEmptyTrimmed()) ? int.MaxValue : AppLogic.AppConfigNativeInt("ProductImage.DisplayLimit");


            for (int i = 0; i < imgCount; i++)
            {
                if (i >= displayLimit) { break; }

                var xmlImg = new XElement("IMAGE");
                xmlImg.Add(new XElement("DEFAULT", imgDefault.src.Equals(imgData.mediumImages[i].src)));

                //large
                var xmlImgLarge = new XElement("LARGE");
                xmlImgLarge.Add(new XElement("ALT", imgData.largeImages[i].Alt));
                xmlImgLarge.Add(new XElement("TITLE", imgData.largeImages[i].Title));
                xmlImgLarge.Add(new XElement("SRC", imgData.largeImages[i].src));
                xmlImg.Add(xmlImgLarge);

                //medium
                var xmlImgMedium = new XElement("MEDIUM");
                xmlImgMedium.Add(new XElement("ALT", imgData.mediumImages[i].Alt));
                xmlImgMedium.Add(new XElement("TITLE", imgData.mediumImages[i].Title));
                xmlImgMedium.Add(new XElement("SRC", imgData.mediumImages[i].src));
                xmlImg.Add(xmlImgMedium);

                //micro
                var xmlImgMicro = new XElement("MICRO");
                xmlImgMicro.Add(new XElement("ALT", imgData.microImages[i].Alt));
                xmlImgMicro.Add(new XElement("TITLE", imgData.microImages[i].Title));
                xmlImgMicro.Add(new XElement("SRC", imgData.microImages[i].src));
                xmlImg.Add(xmlImgMicro);

                xml.Add(xmlImg);
            }
            var xmlpackage = new XmlPackage2("helper.product.xml.config", xml);
            return xmlpackage.TransformString();
        }

        public static bool ProductNotification(string itemCode, int notificationType)
        {
            bool success = false; 
            var ThisCustomer = Customer.Current;
            var loadCmdSet = new string[][] { new string[] {"ECOMMERCENOTIFICATION", "READECOMMERCENOTIFICATION", "@ContactCode", ThisCustomer.ContactCode,
                                                      "@WebsiteCode", InterpriseHelper.ConfigInstance.WebSiteCode, "@ItemCode", itemCode, "@EmailAddress", ThisCustomer.EMail}};

            Interprise.Framework.ECommerce.DatasetGateway.EcommerceNotificationDatasetGateway dsContainer = new Interprise.Framework.ECommerce.DatasetGateway.EcommerceNotificationDatasetGateway();

            if (Interprise.Facade.Base.SimpleFacade.Instance.CurrentBusinessRule.LoadDataSet(InterpriseHelper.ConfigInstance.OnlineCompanyConnectionString, loadCmdSet, dsContainer))
            {
                Interprise.Framework.ECommerce.DatasetGateway.EcommerceNotificationDatasetGateway.EcommerceNotificationRow dsContainerRow;

                if (dsContainer.EcommerceNotification.Rows.Count == 0) { dsContainerRow = dsContainer.EcommerceNotification.NewEcommerceNotificationRow(); }
                else { dsContainerRow = dsContainer.EcommerceNotification[0]; }

                bool onPriceDrop = AppLogic.CheckNotification(ThisCustomer.ContactCode, ThisCustomer.EMail, itemCode, 1);
                bool onItemAvail = AppLogic.CheckNotification(ThisCustomer.ContactCode, ThisCustomer.EMail, itemCode, 1);

                if (notificationType == 1) { onPriceDrop = true; }
                else { onItemAvail = true; }

                dsContainerRow.BeginEdit();
                dsContainerRow.WebSiteCode = InterpriseHelper.ConfigInstance.WebSiteCode;
                dsContainerRow.ItemCode = itemCode;
                dsContainerRow.ContactCode = ThisCustomer.ContactCode;
                dsContainerRow.EmailAddress = ThisCustomer.EMail;
                dsContainerRow.NotifyOnPriceDrop = onPriceDrop;
                dsContainerRow.NotifyOnItemAvail = onItemAvail;
                dsContainerRow.ProductURL = InterpriseHelper.MakeItemLink(itemCode);

                byte[] salt = InterpriseHelper.GenerateSalt();
                byte[] iv = InterpriseHelper.GenerateVector();
                string contactCodeCypher = InterpriseHelper.Encryption(ThisCustomer.ContactCode, salt, iv);
                string emailAddressCypher = InterpriseHelper.Encryption(ThisCustomer.EMail, salt, iv);
                dsContainerRow.EncryptedContactCode = contactCodeCypher + "|" + Convert.ToBase64String(salt) + "|" + Convert.ToBase64String(iv);
                dsContainerRow.EncryptedEmailAddress = emailAddressCypher + "|" + Convert.ToBase64String(salt) + "|" + Convert.ToBase64String(iv);
                dsContainerRow.EndEdit();

                if (dsContainer.EcommerceNotification.Rows.Count == 0) dsContainer.EcommerceNotification.AddEcommerceNotificationRow(dsContainerRow);
                
                var updateCmdSet = new string[][] { new string[] { dsContainer.EcommerceNotification.TableName, "CREATEECOMMERCENOTIFICATION", "UPDATEECOMMERCENOTIFICATION", "DELETEECOMMERCENOTIFICATION"} };

                if (Interprise.Facade.Base.SimpleFacade.Instance.CurrentBusinessRule.UpdateDataset(InterpriseHelper.ConfigInstance.OnlineCompanyConnectionString, updateCmdSet, dsContainer))
                {
                    success = true;
                }

            }
            return success;
        }

        public static List<string> GetCustomerShipTo( string ShipToCode )
        {

            var con = DB.NewSqlConnection();
            var shipToAddress = new List<string>();

            try
            {
                var gridLayout = new StringBuilder();
                con.Open();

                string thisOption = string.Empty;
                string sql = String.Format("SELECT ShipToName, Address, City, State, PostalCode, Country, County, Telephone, Email, AddressType, Plus4 FROM CustomerShipTo WHERE ShipToCode = {0} ", DB.SQuote(ShipToCode));

                var reader = DB.GetRSFormat(con, sql);

                if (reader.Read())
                {

                    shipToAddress.Add(DB.RSField(reader, "ShipToName"));
                    shipToAddress.Add(DB.RSField(reader, "Address"));
                    shipToAddress.Add(DB.RSField(reader, "City"));
                    shipToAddress.Add(DB.RSField(reader, "State"));
                    shipToAddress.Add(CommonLogic.IIF(DB.RSFieldInt(reader, "Plus4") > 0, String.Format("{0}-{1}", DB.RSField(reader, "PostalCode"), DB.RSFieldInt(reader, "Plus4").ToString("0000.##")), DB.RSField(reader, "PostalCode")));
                    shipToAddress.Add(DB.RSField(reader, "Country"));
                    shipToAddress.Add(DB.RSField(reader, "County"));
                    shipToAddress.Add(DB.RSField(reader, "Telephone"));

                    string email = DB.RSField(reader, "Email");
                    if (email.IsNullOrEmptyTrimmed())
                    {
                        email = Customer.Current.EMail;
                    }

                    shipToAddress.Add(email);
                    shipToAddress.Add(DB.RSField(reader, "AddressType"));

                }

                return shipToAddress;

            }
            catch
            {
                throw;
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }

        #region GetContactCodeByEmail

        public static string GetContactCodeByEmail(string emailAddress)
        {
            string contactcode = string.Empty;

            try
            {
                using (SqlConnection con = DB.NewSqlConnection())
                {
                    con.Open();
                    using (IDataReader reader = DB.GetRSFormat(con,
                        "SELECT CC.ContactCode FROM CRMContact CC WITH (NOLOCK) " +
                        "INNER JOIN EcommerceCustomerActiveSites EC  WITH (NOLOCK) " +
                        "ON CC.ContactCode =EC.ContactCode AND EC.IsEnabled = 1  AND EC.WebSiteCode = {0} " +
                        "WHERE CC.Email1 = {1}", DB.SQuote(InterpriseHelper.ConfigInstance.WebSiteCode), DB.SQuote(emailAddress)))
                    {
                        if (reader.Read())
                        {
                            contactcode = DB.RSField(reader, "ContactCode");
                        }
                    }
                }


            }
            catch
            {
                contactcode = string.Empty;
            }

            return contactcode;
        }

        #endregion

        #region Update String Resource Config Value

        public static void UpdateStringResourceConfigValue( string contentKey, string contentValue )
        {
            try
            {
                DB.ExecuteSQL( String.Format("UPDATE ECommerceStringResource SET ConfigValue = {0} WHERE Name = {1} AND LocaleSetting = {2}  AND WebSiteCode = {3}", 
                               DB.SQuote( contentValue.Trim() ), 
                               DB.SQuote( contentKey.Trim() ), 
                               DB.SQuote( Customer.Current.LocaleSetting.ToLowerInvariant() ), 
                               DB.SQuote( InterpriseHelper.ConfigInstance.WebSiteCode )) );
 
                AppLogic.ReloadStringResources();
            }
            catch
            {
                throw;
            }
           
        }

        #endregion

        #region Enable Button(server control) Caption Editing 

        public static void EnableButtonCaptionEditing( Button thisButton, string key )
        {
            thisButton.Attributes.Add("data-contentKey", key);
            thisButton.Attributes.Add("data-contentValue", GetString(key, Customer.Current.SkinID, Customer.Current.LocaleSetting, true));
            thisButton.Attributes.Add("data-contentType", "string resource");
            thisButton.OnClientClick = "return false";
        }

        #endregion

    }

    public static class AppStartLogger
    {
        public static void WriteLine(string Message)
        {
            // don't let logging crash anything itself!
            try
            {
                FileStream fs = new FileStream(CommonLogic.SafeMapPath("images/appstart.log"), FileMode.Append, FileAccess.Write, FileShare.Read | FileShare.Delete);
                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                sw.AutoFlush = true;
                sw.WriteLine("{0:G}: {1}\r\n", DateTime.Now, Message);
                sw.Close();
                fs.Close();
            }
            catch { }
        }

        public static void ResetLog()
        {
            // don't let logging crash anything itself!
            try
            {
                File.Delete(CommonLogic.SafeMapPath("images/appstart.log"));
            }
            catch { }
        }
    }

    public class InterpriseSuiteEcommercePrincipal : IPrincipal
    {
        private Customer m_customer;
        public InterpriseSuiteEcommercePrincipal(Customer customer)
        {
            m_customer = customer;
        }

        #region IPrincipal Members implementation
        public IIdentity Identity
        {
            get
            {
                return m_customer;
            }
        }


        public bool IsInRole(string role)
        {
            return m_customer.Roles.Split(',').Any(r => r.Equals(role, StringComparison.InvariantCultureIgnoreCase));
        }

        #endregion

        #region Public Properties
        public string Roles
        {
            get { return this.m_customer.Roles.ToString(); }
        }

        public Customer ThisCustomer
        {
            get { return m_customer; }
        }
        #endregion
    }


}